1. 程式人生 > >[LeetCode] Ransom Note

[LeetCode] Ransom Note

from struct char function 沒有 spa urn strings can

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

尋找ransomNote中的字母是否由magazine中的字母組成,且每一個在magazine中的字母在ransomNote中只能被使用1次。通過map建立magazine中字母與出現次數的查找表,遍歷ransomNote,如果在map中找到該字母,則讓map中的該字母出現的次數-1,若次數小於0,返回false;如果map中未找到這個字母,返回false。如果遍歷結束仍沒有返回值,說明ransomNote中的字母都是由magazine中的字母組成,返回true。

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        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.count(ransomNote[i])) {
                m[ransomNote[i]]
--; if (m[ransomNote[i]] < 0) return false; } else return false; } return true; } }; // 36 ms

[LeetCode] Ransom Note