leetcode解题: Ransom Note (383)

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

解法1:O(N + M) Time with O(M) Space

经典的用hashtable解决的字母问题,把magazine先hash算出每一个字母出现的次数,然后对ransomNote扫描碰到见过的字母则次数-1,直到所对应的字母的次数小于0(false)或者是可以扫描完所有的ransomNote的字母。
C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
vector<int> map (26);
for (int i = 0; i < magazine.size(); ++i) {
++map[magazine[i] - 'a'];
}
for (int i = 0; i < ransomNote.size(); ++i) {
if (map[ransomNote[i] - 'a'] <= 0) {
return false;
} else {
--map[ransomNote[i] - 'a'];
}
}
return true;
}
};

C++ with std::unordered_map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
unordered_map<char, int> map;
for (int i = 0; i < magazine.size(); ++i) {
map[magazine[i]]++;
}
for (int i = 0; i < ransomNote.size(); ++i) {
if (map[ransomNote[i]] == 0) {
return false;
} else {
--map[ransomNote[i]];
}
}
return true;
}
};

Java

1