题意描述:
给你两个字符串:ransomNote 和 magazine ,判断 ransomNote 能不能由 magazine 里面的字符构成。
如果可以,返回 true ;否则返回 false 。
magazine 中的每个字符只能在 ransomNote 中使用一次。
方法一:暴力解法
C++代码如下:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
for(int i = 0; i<magazine.length(); i++){
for(int j = 0; j<ransomNote.length(); j++){
if(magazine[i] == ransomNote[j]){
ransomNote.erase(ransomNote.begin() + j);
}
}
if(ransomNote.length() == 0){
return true;
}
}
return false;
}
};
时间复杂度: O(n^2)
空间复杂度:O(1)
方法二:利用数组
用一个长度为26的数组还记录magazine里字母出现的次数。然后再用ransomNote去验证这个数组是否包含了ransomNote所需要的所有字母。
C++代码如下:
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int hash[26] = {0};
if(ransomNote.length() > magazine.length()){
return false;
}
for(int i = 0; i < magazine.length(); i++){
hash[magazine[i] - 'a']++;
}
for(int j = 0; j < ransomNote.length(); j++){
hash[ransomNote[j] - 'a']--;
}
for(int k = 0; k < 26; k++){
if(hash[k] < 0){
return false;
}
}
return true;
}
};