LeetCode:有效变形词(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?

思路:

统计两个字符串中各个字母出现次数,以字典形式存储。两个结果字典相同则返回True,否则返回False。

代码(Python):时间 O(n), 空间 O(n)

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        temS = dict()
        temT = dict()
        for item in s:
            temS[item]=0 if (item not in temS) else temS[item]+1
        for item in t:
            temT[item]=0 if (item not in temT) else temT[item]+1
        return True if temS == temT else False

注意:

返回bool类型,在C语言中是0和1,在python中则会将其当成整形。Python中的bool型只有两个值:True、False;

任何时候,注意边界条件。

发布了397 篇原创文章 · 获赞 541 · 访问量 255万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览