您的位置:首页 > 其它

LeetCode-383. Ransom Note

2018-03-05 19:31 309 查看

Description

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


Solution 1(C++)

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> count;
for(int i=0; i<ransomNote.size(); i++){
count[ransomNote[i]]++;
}
for(int j=0; j<magazine.size(); j++){
count[magazine[j]]--;
}
for(auto c:count){
if(c.second>0){ return false; }
}
return true;
}
};


Solution 2(C++)

class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> map(26);
for (int i = 0; i < magazine.size(); ++i)
++map[magazine[i]];
for (int j = 0; j < ransomNote.size(); ++j)
if (--map[ransomNote[j]] < 0)
return false;
return true;
}
};


算法分析

这道题的算法实现比较简单。不啰嗦。

程序分析

解法二与解法一的代码更简洁的地方就是将解法一中额外的检查map中与第二次for循环结合起来了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: