创建于20170308
原文链接:https://leetcode.com/problems/valid-anagram/?tab=Description
1 题目
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?
2 题解:python
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
dict_c={}
#检查s串,并登记s的内容
for i in range(len(s)):
dict_c[s[i]]=dict_c.get(s[i],0)+1 #默认为0
#检查t串,并清空s的内容,如果t和s互为回文,则字典元素个数互相抵消
for i in range(len(t)):
dict_c[t[i]]=dict_c.get(t[i],0)-1 #默认为0
for d in dict_c:
if dict_c[d] != 0:
return False
return True
3 算法分析
这里主要利用回文的概念,t把s的所有元素都恰好用一遍,可以通过统计各个元素出现的次数来进行判断。如果s和t等长且是回文,则所有字符出现的次数是相等的。
时间复杂度为O(n)
空间复杂度为O(n)