# 给定两个由小写字母组成的字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。 # # 示例 1: # # # 输入: s1 = "abc", s2 = "bca" # 输出: true # # # 示例 2: # # # 输入: s1 = "abc", s2 = "bad" # 输出: false # # # 说明: # # # 0 <= len(s1) <= 100 # 0 <= len(s2) <= 100 # # # Related Topics 哈希表 字符串 排序 👍 169 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def CheckPermutation1(self, s1: str, s2: str) -> bool : if len(s1) != len(s2) : return False def CheckPermutation2(self,s1,s2): if len(s1)!=len(s2): return False from collections import defaultdict dic=defaultdict(int) for c in s1: dic[c]+=1 for c in s2: dic[c]-=1 for val in dic.values(): if val!=0: return False return True def CheckPermutation3(self, s1, s2) : if len(s1) != len(s2) : return False ###对s1和s2进行排序 sorted_str1=sorted(s1) sorted_str2=sorted(s2) if sorted_str1==sorted_str2: return True return False def CheckPermutation4(self, s1, s2) : if len(s1) != len(s2) : return False char_count1={} char_count2={} for char in s1: char_count1[char]=char_count1.get(char,0)+ 1 for char in s2: char_count2[char]=char_count2.get(char,0)+ 1 return char_count1==char_count2 def CheckPermutation5(self, s1, s2) : if len(s1) != len(s2) : return False char_count1={} char_count2={} for i in range(len(s1)): char_count1[s1[i]]=char_count1.get(s1[i],0)+1 char_count2[s2[i]] = char_count2.get(s2[i],0)+1 for i in range(len(s1)): c=s1[i] if c in char_count2: if char_count1[c]!=char_count2[c]: return False else: return False return True def CheckPermutation6(self, s1, s2) : ###TODO:异或 if len(s1) != len(s2) : return False flag=0 sumA=0 sumB=0 for i in range(len(s1)): sumA+=ord(s1[i])-ord('a') sumB+=ord(s2[i])-ord('a') flag^= ord(s1[i])-ord('a') flag ^= ord(s2[i]) - ord('a') if sumA!=sumB: return False return flag == 0 def CheckPermutation7(self, s1, s2) : from collections import Counter if len(s1) != len(s2) : return False counter1=Counter(s1) counter2=Counter(s2) return counter1==counter2 def CheckPermutation8(self, s1: str, s2: str) -> bool : # 哈希表 if len(s1) != len(s2) : return False set_char = dict() for char in s1 : if char not in set_char : set_char[char] = 1 else : # mark=ord(char)-ord('a') set_char[char] += 1 for char in s2 : if char not in set_char : return False set_char[char] -= 1 for count in set_char.values() : if count > 0 : return False return True def CheckPermutation9(self, s1: str, s2: str) -> bool : if not s1 or len(s1)==0 or not s2 or len(s2) == 0: return False length=len(s1) if length !=len(s2): return False memory=[0]*26 for i in range(length): memory[ord(s1[i]) - ord('a')]+=1 memory[ord(s2[i]) - ord('a')] -= 1 for num in memory: if num!=0: return False return True sol = Solution() s1 = "abc" s2 = "bca" print(sol.CheckPermutation(s1, s2)) # 输出 True # leetcode submit region end(Prohibit modification and deletion)
力扣刷题_多解法:给定两个由小写字母组成的字符串 s1 和 s2,请编写一个程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。
最新推荐文章于 2024-07-12 16:16:27 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)