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.
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true<Solution>
想法如下
- 使用一個 hash map 來記錄 magazine 出現的字元,以及次數
- 檢查在 ransom note 裡面的字元,是不是存在 hash map 中,以及沒有超過次數
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool canConstruct(string ransomNote, string magazine) { | |
unordered_map<char, int> hashmap; | |
for(const auto &c : magazine) { | |
hashmap[c]++; | |
} | |
for(const auto &c : ransomNote) { | |
if(!hashmap.count(c) || hashmap[c]-- < 1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
}; |
Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public boolean canConstruct(String ransomNote, String magazine) { | |
HashMap<Character, Integer> map = new HashMap<>(); | |
char c; | |
final int magaLen = magazine.length(); | |
for(int i = 0; i < magaLen; i++) { | |
c = magazine.charAt(i); | |
map.put(c, map.getOrDefault(c, 0) + 1); | |
} | |
final int ranLen = ransomNote.length(); | |
for(int i = 0; i < ranLen; i++) { | |
c = ransomNote.charAt(i); | |
if(!map.containsKey(c) || map.put(c, map.get(c)-1) < 1) { | |
return false; | |
} | |
} | |
return true; | |
} | |
} |
沒有留言:
張貼留言