Valid Anagram
Total Accepted: 9718 Total Submissions: 27840My Submissions
Question Solution
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
Hide Similar Problems
Have you met this question in a real interview?
Yes
No
这题采用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)
时间: 2024-11-08 21:49:05