題目: LeetCode - 383. Ransom Note

題目說明

給兩個字串 ransomNotemagazine,求 ransomNote 是否能由 magazine 組成。對於一個字元來說,在 magazine 中出現的次數需大於等於在 ransomNote 中出現的次數。

解題思路

使用一個陣列儲存字元出現的次數即可。由於測資只包含小寫的英文字母,所以陣列大小設為 26。

參考解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int count[26] = {};
for(auto i : ransomNote)
++count[i - 'a'];
for(auto i : magazine)
--count[i - 'a'];
for(auto i : count)
if(i > 0)
return false;
return true;
}
};