leetcode第四題(383. 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.

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可不能這麼用

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章