Python leetcode
242. Valid Anagram
242. Valid Anagram
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.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
猜谜语,就是判断一个字符串的的所有元素和另一个字符串所有元素一样,只是顺序不一样而已
#coding=utf-8
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
#ss = sorted(list(s))
ss = sorted(s)
print ss
#tt = sorted(list(t))
tt = sorted(t)
print tt
return ss==tt
def isAnagram1(self,s,t):
sdict={};tdict={}
for item in s:
sdict[item]=sdict.get(item,0)+1
for item in t:
tdict[item]=tdict.get(item,0)+1
return sdict==tdict
S=Solution()
s='anagram';t='nagaram'
print S.isAnagram1(s,t)

本文介绍了解决LeetCode上242题Valid Anagram的方法,提供了两种实现方案:一种是通过排序后比较字符串,另一种是使用字典计数的方式检查两个字符串是否为字谜互换。
178

被折叠的 条评论
为什么被折叠?



