anagram 相同字母异序词。heart vs earth
1.Our first solution to the anagram problem will check to see that each character in the first string actually occurs in the second. If it is possible to “checkoff” each character, then the two strings must be anagrams. Checking off a character(字母) will be accomplished by replacing it with the special Python value None
. However, since strings in Python are immutable, the first step in the process will be to convert the second string to a list. Each character from the first string can be checked against the characters in the list and if found, checked off by replacement. ActiveCode 1 shows this function.
检测anagram的字符串:第一种方法:主要查看在第一个字符串中每一个单词是否出现在第二个字符串中,相同的字母用None代替,必须将string转变成list,因为,因为字符串不可以修改(immutable)。
1 def anagramSolution1(s1,s2): 2 alist=list(s2) 3 "依次对s1中字母与s2进行比较,只要s1中出现了s2中没有的字母,break" 4 pos1=0;stillok=True 5 6 while pos1<len(s1) and stillok: 7 pos2=0 8 found=False 9 while pos2<len(alist) and not found: 10 if s1[pos1]==alist[pos2]: 11 found=True 12 else: 13 pos2=pos2+1 14 15 if found: 16 alist[pos2]=None 17 else: 18 stillok=False 19 pos1=pos1+1 20 21 return stillok 22
1 def anagramSolution1(s1,s2): 2 alist=list(s2) 3 "依次对s1中字母与s2进行比较,只要s1中出现了s2中没有的字母,break" 4 pos1=0;stillok=True 5 6 while pos1<len(s1) and stillok: 7 8 if s1[pos1] in alist: 9 print s1[pos1],"in alist" 10 pos1=pos1+1 11 continue 12 else: 13 stillok=False 14 15 return stillok
在接下来的计算当中,使用不同的算法,第一种算法的时间复杂度是o(n^2),第二种:先进行排序在进行对比o(nlogn),第三种:brute 暴力破解:o(n!)
对于最后一种算法能够精确到o(n):
we will first count the number of times each character occurs. Since there are 26 possible characters, we can use a list of 26 counters, one for each possible character. Each time we see a particular character, we will increment the counter at that position. In the end, if the two lists of counters are identical, the strings must be anagrams. ActiveCode 3 shows this solution.
这种算法根据单词26个字母特性,建立一个list,对26个字母遍历string S1 ,string S2,最后比较相同变换趋势。
1 def anagramSolution2(s1,s2): 2 alist1=[0]*26 3 alist2=[0]*26 4 5 for i in range(len(s1)): 6 "ord C中 int,将ascall强制转换成integer" 7 posi=ord(s1[i])-ord(‘a‘) 8 alist1[posi]+=1 9 10 for i in range(len(s2)): 11 "ord C中 int,将ascall强制转换成integer" 12 posi=ord(s2[i])-ord(‘a‘) 13 alist2[posi]+=1 14 matched=True 15 i=0 16 while i< 26 and matched: 17 if alist1[i]==alist2[i]: 18 i+=1 19 else: 20 matched=False 21 22 return matched
在所有的复杂度中最好能够缩减到o(n)和log(n)的时间复杂度,超过o(n^2)时间复杂度的算法必须要对算法进行改近