题目:
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
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
思路:
先给大家解题意,这题真拐了好大圈,又是勒索信又是杂志的,其实就是一个字符出现频数的问题。笔者最开始方向搞错,当成了包含字符问题,结果各种错。上网找了这题大意才勉强了解题意,只能说这题不难,但是想看明白题意确实挺难TOT~~~我在代码中加入了注释,这样会更好理解一些。
这里如果想自己用编译器测试的话,建议不要使用他给的案例,偶然性很大,笔者给出一个案例,大家可以自己尝试使用。如果返回值对了,证明应该是正确的结果:
canConstruct(""fffbfg"", ""effjfggbffjdgbjjhhdegh"")
期望结果为true
代码:
public boolean canConstruct(String ransomNote, String magazine) {
Map<Character,Integer> charmap = new HashMap<>();
//循环把杂志中出现的单个字符计数,确定每个字符的出现频数~~
for(int i = 0; i<magazine.length(); i++) {
char c = magazine.charAt(i);
if (charmap.containsKey(c)) {
int count = (int)charmap.get(c);
count++;
charmap.put(c, count);
}else {
charmap.put(c, 1);
}
}
//循环勒索信字符,每出现杂志中存在的字符,就把杂志中此字符频数减一。循环中,如果没得减了,就确定其无法构成信件!
for(int i = 0; i<ransomNote.length() ;i++) {
char c = ransomNote.charAt(i);
if (charmap.containsKey(c)) {
int count = (int)charmap.get(c);
count--;
if (count<0) {
return false;
}else {
charmap.put(c, count);
}
}else {
return false;
}
}
return true;
}