383. Ransom Note

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int n = ransomNote.size(), m = magazine.size();
if(n>m) return false;
vector<int> vec(26,0);
for(char c:magazine) vec[c-'a']++;
for(char c:ransomNote){
vec[c-'a']--;
if(vec[c-'a']<0) return false;
}
return true;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)