leetCode 383. Ransom Note 字符串

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

題目大意:

有一個隨機串,有一個大串。判斷隨機串是否爲大串的組成部分。

隨機串某一字符的個數必須小於大串。隨機串中出現的字符大串中必須都有。

思路:

用map/unordered_map來處理大串,將字符的個數以及種類記錄在map/unordered_map中。然後進行判斷。

代碼如下:

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        if(ransomNote.size() == 0)
            return true;
        unordered_map<char,int> m;
        for(int i = 0;i < magazine.size();i++)
        {
            m[magazine[i]]++;
        }
        for(int i = 0 ; i < ransomNote.size(); i++)
        {
            if(m.find(ransomNote[i]) == m.end() || m[ransomNote[i]] == 0 )
                return false;
            m[ransomNote[i]]--;
        }
        
        return true;
    }
};

經過測試126組數據,使用map耗時132ms,使用unordered_map耗時84ms。所以在不需要map有序的情況下,使用unordered_map是首選。


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