| 1 | class AnagramDetection: |
| 2 | # 先对两个字符串进行list化 |
| 3 | # 对字符串对应的两个list进行排序 |
| 4 | # 依次比较字符是否匹配 |
| 5 | def anagramSolution1(self, s1, s2): |
| 6 | alist1 = list(s1) |
| 7 | alist2 = list(s2) |
| 8 | |
| 9 | alist1.sort() |
| 10 | alist2.sort() |
| 11 | |
| 12 | pos = 0 |
| 13 | matches = True |
| 14 | |
| 15 | while pos < len(s1) and matches: |
| 16 | if alist1[pos] == alist2[pos]: |
| 17 | pos = pos + 1 |
| 18 | else: |
| 19 | matches = False |
| 20 | |
| 21 | return matches |
| 22 | |
| 23 | # 首先生成两个26个字母的list |
| 24 | # 计算每个字母出现的次数并存入到相应的list中 |
| 25 | # 比较两个list是否相同 |
| 26 | def anagramSolution2(self, s1, s2): |
| 27 | c1 = [0] * 26 |
| 28 | c2 = [0] * 26 |
| 29 | |
| 30 | for i in range(len(s1)): |
| 31 | pos = ord(s1[i]) - ord('a') |
| 32 | c1[pos] = c1[pos] + 1 |
| 33 | |
| 34 | for i in range(len(s2)): |
| 35 | pos = ord(s2[i]) - ord('a') |
| 36 | c2[pos] = c2[pos] + 1 |
| 37 | |
| 38 | j = 0 |
| 39 | stillOK = True |
| 40 | while j < 26 and stillOK: |
| 41 | if c1[j] == c2[j]: |
| 42 | j = j + 1 |
| 43 | else: |
| 44 | stillOK = False |
| 45 | |
| 46 | return stillOK |
| 47 | |
| 48 | # 首先将两个字符串list化 |
| 49 | # 将两个list中的字符生成两个set |
| 50 | # 比较两个set, 如果不相等直接返回false |
| 51 | # 如果两个set相等, 比较每个set中字符在相应list中的个数, 个数不同返回false |
| 52 | def anagramSolution3(self, s1, s2): |
| 53 | alist1 = list(s1) |
| 54 | alist2 = list(s2) |
| 55 | |
| 56 | aset1 = set(alist1) |
| 57 | aset2 = set(alist2) |
| 58 | |
| 59 | if aset1 != aset2: |
| 60 | return False |