跳至主要内容

383. Ransom Note

· 閱讀時間約 1 分鐘
class Solution {
public:
bool canConstruct(string ransomNote, string magazine)
{
vector<int> freq(26);

for(auto& c : magazine) ++freq[ c - 'a'];

for(int i = 0; i < ransomNote.size(); i++)
{
int c = ransomNote[i] - 'a';
if (--freq[c] < 0) return false;
}
return true;
}
};
  • T: $O(N)$
  • S: $O(1)$