LeetCode 383.贖金信(Ransom Note)C C++
阿新 • • 發佈:2018-12-21
給定一個贖金信 (ransom) 字串和一個雜誌(magazine)字串,判斷第一個字串ransom能不能由第二個字串magazines裡面的字元構成。如果可以構成,返回 true ;否則返回 false。
(題目說明:為了不暴露贖金信字跡,要從雜誌上搜索各個需要的字母,組成單詞來表達意思。)
注意:
你可以假設兩個字串均只含有小寫字母。
示例:
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true
此題大概意思就是找到ransom中的每個字母出現的總次數是否小於等於magazine中相同字母出現的次數,如果某個字母超過magazine中相同字母出現的次數,則返回false
C 程式碼:
bool canConstruct(char* ransomNote, char* magazine) { int k=0; int len1 = strlen(ransomNote); int len2 = strlen(magazine); int pt[26] = {0}; int tr[26] = {0}; for (int i=0;i <len2;i++) pt[magazine[i]-'a']++; for (int j=0;j <len1;j++) tr[ransomNote[j]-'a']++; while (k < 26 &&tr[k] <= pt[k]) k++; return k == 26; }
C++ 程式碼: 我寫了兩種遍歷map容器的方法
class Solution { public: bool canConstruct(string ransomNote, string magazine) { map<char,int> ar; int i; for (i = 0;i < magazine.size();i++) { ar[magazine[i]]++; } map<char,int> ar2; for (i = 0;i < ransomNote.size();i++) { ar2[ransomNote[i]]++; } map<char,int>::iterator it; // for (auto &it : ar2) for (it = ar2.begin();it != ar2.end();it++) { //if (it.second > ar[it.first]) if (it->second > ar[it->first]) return false; } return true; } };
謝謝。