leetcode第四題(383. Ransom Note)
阿新 • • 發佈:2018-11-15
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
這道題目不要誤解了,不是子集的意思,實際上是後者的元素夠不夠組成前面的字串,比較簡單的思想就是利用26字母進行計數
這裡用的是unordermap(雜湊表), 也可以用陣列,下標用‘magzine[i]’-'a'來表示
#include <iostream> #include <string> #include <unordered_map> using namespace std; bool canConstruct(string ransomNote, string magazine) { int ran_num = ransomNote.length(); int mag_num = magazine.length(); unordered_map <char,int> map(26); for (int i = 0; i < mag_num; ++i) { ++map[magazine[i]]; } for (int j = 0; j < ran_num; ++j) { if(--map[magazine[j]]<0) return false; } return true; } int main() { std::string a = "aa"; std::string b = "aab"; unordered_map<char ,int > test(10); std::cout<<test['a']<<endl; std::cout << canConstruct(a,b) << std::endl; return 0; }
這裡要注意的是,當申明unordered_map <char,int> map(26);
當我們直接出一個char的時候,int預設為0.
注意雜湊表和map的區別,map可不能這麼用