1 解题思想
最近比较忙,没时间更新了都。。
这道题是给了两个字符串,ransomNote和magazine,问magazine的字母能否组成ransomNote,magazine没有的字符不能用,某个字母出现了n次,那么在构造ransomNote 时,可以使用0~n次,反正不能超过。
其实解法,也就是统计下magazine 26个字母的分布,看看够不够ransomNote的就好
2 原题
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
3 AC解
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
int counter[] = new int[26];
for(int i=0;i<magazine.length();i++)
counter[magazine.charAt(i) - 'a'] ++;
for(int i=0;i<ransomNote.length();i++) {
counter[ransomNote.charAt(i) -'a'] --;
if (counter[ransomNote.charAt(i) -'a'] < 0 ) {
return false;
}
}
return true;
}
}