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
思路:
统计两个字符串中各个字符的数量,如果第一个字符串中每个字符数量都小于第二个字符串对应字符的数量,则返回true;否则,返回false。
方法1. 使用两个map<char,int>分别统计每个字符串中每个字符的数量,然后判断第一个字符串中字符数量是否是否小于第二个字符串中对应字符的字符数量。
方法2. 使用一个map,首先遍历第一个字符串,统计每个字符数量;然后遍历第二个字符串,遇见对应字符,字符数量减1;最后遍历map,如果所有字符数量均大于0,则返回true,否则返回false。
Code1:
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
map<string,int> comResM;
vector<string> comRes;
vector<string> :: iterator it;
int l1,l2;
int sum=list1.size()+list2.size();
for(int i=0;i<list1.size();i++){
it = find(list2.begin(),list2.end(),list1[i]);
if(it!=list2.end()){
l1=i;
l2=distance(list2.begin(),it);
comResM[list1[i]] = l1+l2;
if((l1+l2)<sum) sum=l1+l2;
}
}
for(auto & n:comResM){
if(n.second==sum) comRes.push_back(n.first);
}
return comRes;
}
};
Code2:
class Solution {
public:
vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {
unordered_map<string, int> hash1;
for (int i = 0; i < list1.size(); i++) {
hash1[list1[i]] = i;
}
unordered_map<int, vector<string> > ans;
int min = 99999999;
for (int j = 0; j < list2.size(); j++) {
auto got = hash1.find(list2[j]);
if (got != hash1.end()) {
int common = got->second + j;
if (common <= min) {
min = common;
ans[min].push_back(list2[j]);
}
}
}
return ans[min];
}
};