天天看点

LeetCode: Valid Anagram

题目:给定两个字符串s和t,写出一个程序判断s是否为t的回文字符串。

例:s=”anagram”, t=”nagaram” 返回true

s=”car”, t=”ant” 返回false

解题思路1:使用sorted函数,将字符串排序,如:

sorted(s)=[‘a’,’a’,’a’,’g’,’m’,’n’,’r’],

sorted(t)=[‘a’,’a’,’a’,’g’,’m’,’n’,’r’]

代码1:

class Solution(object):
def isAnagram(self, s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    return(sorted(s)==sorted(t))
           

解题思路2:使用2个字典,分别将2个字符串中每个字母作为key,每个字母出现次数作为value,使用如下语句计数:

dic1[item] = dic1.get(item, 0) + 1
           

代码2:

class Solution(object):
def isAnagram(self, s, t):
    """
    :type s: str
    :type t: str
    :rtype: bool
    """
    dic1,dic2={},{}
    for item in s:
        dic1[item] = dic1.get(item,0)+1
    for item in t:
        dic2[item]  dic.get(item,0)+1
    return (dic1==dic2)
           

解题思路3:使用1个字典,将字符串中每个字母作为key,每个字母出现次数作为value ,s中出现1个字符,字典key值对应的value加1,t中出现相同字符,字典key值对应的value减1.

代码3:

from collections import defaultdict #标准字典库
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t): #首先判断长度是否相同
            return False
        else:
            dic = defaultdict(int)
            for i in range(len(t)): 
                dic[s[i]] +=1 
                """
      s[i]为字符串中的字母,dic[s[i]]为字母所对应的key值
                """
                dic[t[i]] -=1
            for key,value in dic.iteritems():
                if value !=0:
                    return False
        return True