2017年12月15日 星期五

[LeetCode] 383. Ransom Note

轉自LeetCode

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
<Solution>
想法如下
  • 使用一個 hash map 來記錄 magazine 出現的字元,以及次數
  • 檢查在 ransom note 裡面的字元,是不是存在 hash map 中,以及沒有超過次數
code 如下

C++
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;
}
};
view raw ransomNote.cpp hosted with ❤ by GitHub

Java
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;
}
}
view raw ransomNote.java hosted with ❤ by GitHub

沒有留言:

張貼留言