Leetcode Algorithm No.242 Valid Anagram
2015-09-08 10:14
344 查看
问题描述:
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)
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)
相关文章推荐
- 【Django】template中实现加减乘除数学运算[加法 减法 乘法 除法]
- oc中protocol、category和继承的区别
- oc中protocol、category和继承的区别
- 【Django】 终端打印出错信息
- 【Django】 密码加密
- 【Django】 国际化
- [译]Google新logo是如何缩减13000字节的
- 【Django】 上传图片
- uva 11090 Going in Cycle!! 平均权值最小的回路
- 15条谷歌轶事
- 【音乐分享】Let Me Go
- Google Chrome 快捷方式
- 【英语】Bingo口语笔记(71) - shit系列
- 【英语】Bingo口语笔记(70) - 最易忽略的2个连读技巧
- uva 11090 - Going in Cycle!!(二分+BellmanFord)
- vim如何配置go语言环境
- GoogleTest的使用01
- R语言包_googleVis
- go语言 interface 初探
- hdu 1853 Cyclic Tour /3488 Going Home 费用流判环