Leetcode383
1.问题描述
1.杂志里的字符不可重复使用,相当于第一个字符串是第二个字符串的子序列
2.都是小写字母
2.解决方案
解法一:暴力
不多说了,就两个for硬遍历!
// 时间复杂度: O(n^2)
// 空间复杂度:O(1)
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++) {
// 在ransomNote中找到和magazine相同的字符
if (magazine[i] == ransomNote[j]) {
ransomNote.erase(ransomNote.begin() + j); // ransomNote删除这个字符,很费时间
break;
}
}
}
// 如果ransomNote为空,则说明magazine的字符可以组成ransomNote
if (ransomNote.length() == 0) {
return true;
}
return false;
}
};
解法二:哈希
代码一样的,但是由于是26个小写字母,所以用数组会更快一点int record[26] = {0},我这边先给出unordered_map的代码!
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
//1.建立哈希表
unordered_map<char,int> mp;
for (auto item: magazine) {
mp[item]++;
}
//2.
for (auto item: ransomNote) {
if(mp.find(item)!=mp.end()){
mp[item]--;
if(mp[item]==0) mp.erase(item);
}
else return false;
}
return true;
}
};