LeetCode之383. Ransom Note
2016-10-25 19:35
423 查看
--------------------------------------------
思路就是进行频率统计。
统计一下第二个字符串字符出现次数++
统计一下第一个字符串中字符出现次数--
如果出现负数说明第二个中的字符不够用的。
AC代码如下:
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { int book[]=new int[26]; for(int i=0;i<magazine.length();i++) book[magazine.charAt(i)-'a']++; for(int i=0;i<ransomNote.length();i++) book[ransomNote.charAt(i)-'a']--; for(int i=0;i<book.length;i++) if(book[i]<0) return false; return true; } }
改进的AC代码(节省了一个for循环):
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { int book[]=new int[26]; for(int i=0;i<magazine.length();i++) book[magazine.charAt(i)-'a']++; for(int i=0;i<ransomNote.length();i++) if(--book[ransomNote.charAt(i)-'a']<0) return false; return true; } }
或者:
统计一下第一个的字符出现次数++;
统计一下第二个字符出现次数--
如果出现正数说明第一个没减完呗
AC代码:
public class Solution { public boolean canConstruct(String ransomNote, String magazine) { int book[]=new int[26]; for(int i=0;i<ransomNote.length();i++) book[ransomNote.charAt(i)-'a']++; for(int i=0;i<magazine.length();i++) book[magazine.charAt(i)-'a']--; for(int i=0;i<book.length;i++) if(book[i]>0) return false; return true; } }
相关文章推荐
- LeetCode 383. Ransom Note
- LeetCode-383. Ransom Note
- leetcode题解-58. Length of Last Word && 67. Add Binary && 383. Ransom Note
- LeetCode 383. Ransom Note
- LeetCode 383. Ransom Note 解题报告
- leetcode 383. Ransom Note 勒索信
- 【Leetcode】383. Ransom Note
- Leetcode383. Ransom Note
- LeetCode - 383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode 383. Ransom Note(java)
- leetcode 383. Ransom Note
- LeetCode笔记:383. Ransom Note
- LeetCode-383. Ransom Note
- leetcode 383. Ransom Note
- LeetCode 383. Ransom Note 题解(C++)
- leetcode 383. Ransom Note HashMap 统计字符 + HashMap
- 小白笔记--------------leetcode(383. Ransom Note)
- LeetCode_383. Ransom Note
- Leetcode - String - 383. Ransom Note(水题)