码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_242——Valid Anagram (字典法)

时间:2015-08-09 18:23:47      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

Valid Anagram

 Total Accepted: 9718 Total Submissions: 27840My Submissions

 

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

 

Hide Tags
 Hash Table Sort
Hide Similar Problems
 (M) Anagrams
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

这题采用python语言来编写:

注意:在python中字典中没有的键不能直接赋值

 1 class Solution:
 2     def isAnagram(self,s,t):
 3         a1=[‘a‘,‘b‘,‘c‘,‘d‘,‘e‘,‘f‘,‘g‘,‘h‘,‘i‘,‘j‘,‘k‘,‘l‘,‘m‘, 4             ‘n‘,‘o‘,‘p‘,‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘]
 5         a2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 6             0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
 7         hash1=dict(zip(a1,a2))
 8         hash2=dict(zip(a1,a2))
 9         for i in list(s):
10             hash1[i]+=1
11         for i in list(t):
12             hash2[i]+=1
13 
14         for a in hash1:
15             if hash1[a]!=hash2[a]:
16                 return False
17         for a in hash2:
18             if hash2[a]!=hash1[a]:
19                 return False
20         return True
21 
22 def main():
23     s=‘nl‘
24     t=‘cx‘
25     v=Solution()
26     re=v.isAnagram(s,t)
27     print(re)

 

 

leetcode_242——Valid Anagram (字典法)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4715384.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!