问题描述:
Giventwo strings s and t, write a function to determineif t is an anagram of s.
Forexample,
s = "anagram", t = "nagaram",return true.
s = "rat", t = "car", returnfalse.
Note:
You may assume the string contains only lowercase alphabets.
解决方法:
一共有26个字母,为每个字母对应一个素数,让每个字母对应的素数都不相同。
将字符串s中所有出现过的字母所对应的素数相乘,会得到一个很大的乘数。
用这个乘数除以t字符串中所有出现过的字母对应的素数,全部可以除尽则说明是anagram.
Python 代码如下(python3.4)
def isAnagram(self, s, t): reference = {'a':2,'b':3,'c':5,'d':7,'e':11,'f':13,'g':17,'h':21,'i':23,'j':31,'k':37,'l':41,'m':43,'n':47,'o':51,'p':53,'q':57,'r':61,'s':67,'t':71,'u':79,'v':87,'w':91,'x':101,'y':103,'z':107} i=0 products = 1 while i< len(s): products = products * reference[s[i]] i=i+1 i=0 productt = 1 while i< len(t): productt = productt * reference[t[i]] i=i+1 if productt == products: return True else: return False s = "anagram" t = "nagaram" out=isAnagram(1, s, t) print(out)