给定一个任意的表示勒索信内容的字符串,和另一个字符串表示杂志的内容,写一个方法判断能否通过剪下杂志中的内容来构造出这封勒索信,若可以,返回 true;否则返回 false。
杂志字符串中的每一个字符仅能在勒索信中使用一次。
样例
样例 1
输入 : ransomNote = "aa", magazine = "aab"
输出 : true
解析 : 勒索信的内容可以有杂志内容剪辑而来
样例 2
输入 : ransomNote = "aaa", magazine = "aab"
输出 : false
解析 : 勒索信的内容无法从杂志内容中剪辑而来
注意事项
你可以认为两个字符串都只包含小写字母。
解题思路1:
刚开始把题目理解错了,以为是一道字符子串匹配问题,结果后来才发现是一个字符串包含问题。题干的意思是说给定两个字符串分别为ransomNote和magazine,我们要写一个function来判断ransomNote是否能由magazine字符串中的字母组成,而且每个出现在magazine中的字母只能在ransomNote中出现一次。
其实就是要看magazine中的字符是否全部包含了ransomNote的字符,转换成数学关系:magazine-ransomNode>=0, return true;
参考大神思路:由于字符串是由26个小写英文字母组成的,所以我们可以声明一个大小为26的int类型数组,代表26个英文字母和它们出现的次数,其实这里用“出现的次数”代表数组中的数字是不太妥当的,数组中数字的变化更像是生产者和消费者的关系,magazine是生产者,生产出一种字母就在其对应的位置上“加一”,ransomNote是消费者,每“消费”一个字母就在其对应的位置上“减一”。如果ransomNote能够由magazine构成,那么数组所有的位置上肯定都是非负的,如果是负数说明ransomNote消费的,magazine根本生产不了那么多,产能不足自然无法构成ransomNote。大致就是这么一个道理,代码如下:
class Solution {
public:
/**
* @param ransomNote: a string
* @param magazine: a string
* @return: whether the ransom note can be constructed from the magazines
*/
bool canConstruct(string &ransomNote, string &magazine)
{
// Write your code here
int a[26] = {0};
for(int i=0;i<magazine.size();i++)
a[magazine[i]-'a']++;
for(int i=0;i<ransomNote.size();i++)
if(--a[ransomNote[i]-'a']<0)
return false;
return true;
}
};
解题思路2:
思路同上,只是使用STL中的哈希表数据结构。
class Solution {
public:
/**
* @param ransomNote: a string
* @param magazine: a string
* @return: whether the ransom note can be constructed from the magazines
*/
bool canConstruct(string &ransomNote, string &magazine)
{
// Write your code here
unordered_map<char, int> m;
for (char c : magazine)
++m[c];
for (char c : ransomNote)
if (--m[c] < 0)
return false;
return true;
}
};
最近提交:
public class Solution {
/**
* @param ransomNote: a string
* @param magazine: a string
* @return: whether the ransom note can be constructed from the magazines
*/
public boolean canConstruct(String ransomNote, String magazine) {
// Write your code here
char[] r = ransomNote.toCharArray();
char[] m = magazine.toCharArray();
if(r.length == 0)
return true;
//map存储r的字母与次数
Map<Character, Integer> map = new HashMap<>();
for(char c : r){
if(map.get(c) != null)
map.put(c, map.get(c)+1);
else
map.put(c, 1);
}
//遍历m,将map中出现的字母依次减一
for(char c : m)
if(map.get(c) != null)
map.put(c, map.get(c)-1);
//最后剩下map中,若还存在有次数大于0的,说明m中并未全部减去,即不能构造
for(char c : map.keySet())
if(map.get(c) > 0)
return false;
return true;
}
}