题意:
给定两个小写字母构成的字符串,判断前者是否能由后者字符串中的字母组成,而且每个出现在后者中的字母只能在前者中出现一次(一一匹配)。
初步分析:
就是说前者字符串中的所有字母后者字符串中都要有,而且数目还必须等于或者大于前者。
用map存储前者每个字母有多少个,然后遍历后者,对于map中有的(前者字符串有的),就将map中value值减1
最后如果不存在value值大于0的,返回真(代表前者字符串的字母都被后者匹配完了),否则返回假
public class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
HashMap<Character, Integer> hm = new HashMap<>();
for(int i=0; i<ransomNote.length(); i++)
{
if(!hm.containsKey(ransomNote.charAt(i)))
hm.put(ransomNote.charAt(i),1);
else
hm.put(ransomNote.charAt(i),hm.get(ransomNote.charAt(i))+1);
}
for(int i=0; i<magazine.length(); i++)
{
if(hm.containsKey(magazine.charAt(i)))
hm.put(magazine.charAt(i),hm.get(magazine.charAt(i))-1);
}
for (Map.Entry<Character, Integer> entry : hm.entrySet())
{
if(entry.getValue() > 0)
return false;
}
return true;
}
}
其实用角标和角标对应值来描述关系,也就是说,用数组来当做map用是常有的事,所以,参看这种解法:
public boolean canConstruct(String ransomNote, String magazine) {
int[] table = new int[128];
for (char c : magazine.toCharArray())
table[c]++;
for (char c : ransomNote.toCharArray())
if (--table[c] < 0)
return false;
return true;
}
意思一样的,这样更方便