class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: if len(s1) != len(s2): return False base = set(s1+s2) for b in base: if s1.count(b) != s2.count(b): return False return True
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: if len(s1) != len(s2): return False base = [chr(i) for i in range(ord("a"),ord("z")+1)] for b in base: if s1.count(b) != s2.count(b): return False return True
+
+
再进一步,为了直观,我们可以引入string包,代码如下:
+
1 2 3 4 5 6 7 8 9 10
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: import string if len(s1) != len(s2): return False for b in string.ascii_lowercase: if s1.count(b) != s2.count(b): return False return True
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: if len(s1) != len(s2): return False base = set(s1+s2) for b in base: if s1.count(b) != s2.count(b): return False return True
+
+
另外含高级数据结构的三种解法
+
解法1:
+
1 2 3 4
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: from collections import Counter return Counter(s1) == Counter(s2)
class Solution: def CheckPermutation(self, s1: str, s2: str) -> bool: import string if len(s1) != len(s2): return False for b in string.ascii_lowercase: if s1.count(b) != s2.count(b): return False return True