1、Ransom Note
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.
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
判断第一个字符串是否能由第二个字符串的某部分组成嗯~
就是保证第一个字符串的每一种字符的个数小于等于第二个字符串的,可以用删除法判断。第二种会快一点
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char,int> result;
for(char i : magazine)
result[i]++;// first=i的second++;
for(char i : ransomNote){
result[i]--;
if(result[i] == -1)
return false;
}
return true;
}
};
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int i = 0;
int length = ransomNote.size();
for(;i < length; i++){
auto tem = find(magazine.begin(), magazine.end(), ransomNote[i]);
if(tem == magazine.end())
break;
magazine.erase(tem);
}
if(i == length)
return true;
return false;
}
};
1、for(char i : ransomNote)
等价于:
for(int a = 0; a < ransomNote.size(); a++)
char i = ransomNote[a];
2、InputIterator find (InputIterator first, InputIterator last, const T& val);
若存在val,返回它的迭代器,不存在返回last。复杂度为O(n)。
3、string& erase ( size_t pos = 0, size_t n = npos );
iterator erase ( iterator position );
iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)