Leetcode学习(40)—— 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):
        dic1 = dic2 = {}
        for i in s:
            dic1[i] = dic1.get(i, 0) + 1
        for j in t:
            dic2[j] = dic2.get(j, 0) + 1
        return dic1 == dic2



'''
class Solution(object):
    def isAnagram(self, s, t):
        return sorted(s) == sorted(t)
'''

字典求解:
时间复杂度为 O(n)

Leetcode学习(40)—— Valid Anagram_第1张图片


排序求解:
时间复杂度为 O(nlogn)

Leetcode学习(40)—— Valid Anagram_第2张图片

你可能感兴趣的:(Leetcode)