[LeetCode] Check If a String Can Break Another String

1433. Check If a String Can Break Another String

Given two strings: s1 and s2 with the same size, check if some permutation of string s1 can break some permutation of string s2 or vice-versa. In other words s2 can break s1 or vice-versa.

A string x can break string y (both of size n) if x[i] >= y[i] (in alphabetical order) for all i between 0 and n-1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool checkIfCanBreak(string s1, string s2) {
sort(begin(s1), end(s1));
sort(begin(s2), end(s2));
int compare = 0;
for(int i = 0; i < s1.length(); i++) {
if(s1[i] == s2[i]) continue;
if(s1[i] > s2[i]) {
if(compare == 0) compare = 1;
else if(compare == -1) return false;
} else {
if(compare == 0) compare = -1;
else if(compare == 1) return false;
}
}
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/03/PS/LeetCode/check-if-a-string-can-break-another-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.