Skip to content

Commit ac17bf3

Browse files
authored
Create ransom-note.cpp
1 parent 121947d commit ac17bf3

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

C++/ransom-note.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
bool canConstruct(string ransomNote, string magazine) {
7+
vector<int> counts(26);
8+
int letters = 0;
9+
for (const auto& c : ransomNote) {
10+
if (counts[c - 'a']++ == 0) {
11+
++letters;
12+
}
13+
}
14+
for (const auto& c : magazine) {
15+
if (--counts[c - 'a'] == 0 && --letters == 0) {
16+
// Break as soon as possible if letters have been enough.
17+
break;
18+
}
19+
}
20+
return letters == 0;
21+
}
22+
};

0 commit comments

Comments
 (0)