[leetcode] 1433. Check If a String Can Break Another String
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
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.
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,问是否存在一个排列s1中的每个字符都大于s2,相反也可以。我的办法很直接,如果把s1和s2的字母从小到大进行排序,然后一个一个的比较就知道是否是都大于还是都小于了,对于相同字符的位置,跳过去就行了。如果既存在大于的情况又存在小于的情况,直接返回False就可以。
我看了一下其他人的答案,思路差不多,都是先进行排序。
代码
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
arr1=list(s1)
arr2=list(s2)
arr1.sort()
arr2.sort()
n=min(len(arr1),len(arr2))
cnt1=0
cnt2=0
for i in range(n):
if(arr1[i]<arr2[i]):
cnt1+=1
elif(arr1[i]>arr2[i]):
cnt2+=1
if(cnt1 and cnt2):
return False
return True
参考文献
[LeetCode] Python 3 Two Solutions Explained