[leetcode, medium] 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).
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.
Example 1:
Input: s1 = "abc", s2 = "xya" Output: true Explanation: "ayx" is a permutation of s2="xya" which can break to string "abc" which is a permutation of s1="abc".
Example 2:
Input: s1 = "abe", s2 = "acd" Output: false Explanation: All permutations for s1="abe" are: "abe", "aeb", "bae", "bea", "eab" and "eba" and all permutation for s2="acd" are: "acd", "adc", "cad", "cda", "dac" and "dca". However, there is not any permutation from s1 which can break some permutation from s2 and vice-versa.
Example 3:
Input: s1 = "leetcodee", s2 = "interview" Output: true
Constraints:
- s1.length == n
- s2.length == n
- 1 <= n <= 10^5
- All strings consist of lowercase English letters.
문제를 간단히 설명하면
문자열 두개가 주어지는데 (s1, s2)
이 문자열 두개를 각각 순열 시켜서 모든 경우의 수를 구한다.
그리고 두 문자열의 모든 순열 케이스 끼리 1:1매칭 했을때
한쪽이 다른 한쪽보다 문자열코드가 같거나 더 큰 경우 true를 리턴하고 아닌경우 false를 리턴한다.
const checkIfCanBreak = function(s1, s2) {
const sorted1 = s1.split('').sort();
const sorted2 = s2.split('').sort();
let canbreak1 = true;
let canbreak2 = true;
for(let i=0; i<sorted1.length; i++) {
if(sorted1[i] > sorted2[i]) canbreak1 = false;
if(sorted1[i] < sorted2[i]) canbreak2 = false;
}
return canbreak1 || canbreak2;
};
두 문자열을 정렬 한다음,
문제에서의 실패 조건을 체크하면 된다.
이런 풀이가 가능한 이유는 A string x can break string y 이기 때문이다.
할수있다의 의미는 1개의 케이스만 나와도 성공한다는것이므로 두 문자열을 애초에 정렬한다음 비교하면 된다.
예를들어, s1의 첫번째 문자와 s2의 첫번째 문자는 서로 비슷한 문자코드이도록 배치해야 string x가 string y를 break할 수 있는지를 체크 할 수 있다.