Skip to content

Commit 1f9ce1c

Browse files
authored
Update check-if-a-string-can-break-another-string.cpp
1 parent 1a078d9 commit 1f9ce1c

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

C++/check-if-a-string-can-break-another-string.cpp

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,38 @@
1-
// Time: O(nlogn)
1+
// Time: O(n)
22
// Space: O(1)
33

44
class Solution {
5+
public:
6+
bool checkIfCanBreak(string s1, string s2) {
7+
const auto& count1 = counter(s1), &count2 = counter(s2);
8+
return isBreak(count1, count2) || isBreak(count2, count1);
9+
}
10+
11+
private:
12+
bool isBreak(const vector<int>& count1, const const vector<int>& count2) {
13+
int curr1 = 0, curr2 = 0;
14+
for (int c = 0; c < 26; ++c) {
15+
curr1 += count1[c];
16+
curr2 += count2[c];
17+
if (curr1 < curr2) {
18+
return false;
19+
}
20+
}
21+
return true;
22+
}
23+
24+
vector<int> counter(const string& word) {
25+
vector<int> count(26);
26+
for (const auto& c : word) {
27+
++count[c - 'a'];
28+
}
29+
return count;
30+
}
31+
};
32+
33+
// Time: O(nlogn)
34+
// Space: O(1)
35+
class Solution2 {
536
public:
637
bool checkIfCanBreak(string s1, string s2) {
738
sort(begin(s1), end(s1)), sort(begin(s2), end(s2));
@@ -10,20 +41,20 @@ class Solution {
1041
if (s1[i] < s2[i]) {
1142
flag1 = false;
1243
}
13-
if (s2[i] < s1[i]) {
44+
if (s2[i] < s1[i]) {
1445
flag2 = false;
1546
}
1647
if (!flag1 && !flag2) {
1748
return false;
1849
}
1950
}
20-
return true;
51+
return true;
2152
}
2253
};
2354

2455
// Time: O(nlogn)
2556
// Space: O(1)
26-
class Solution2 {
57+
class Solution3 {
2758
public:
2859
bool checkIfCanBreak(string s1, string s2) {
2960
sort(begin(s1), end(s1)), sort(begin(s2), end(s2));

0 commit comments

Comments
 (0)