KK's blog

每天积累多一些

0%

LeetCode 242 Valid Anagram

LeetCode



Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Example 1:

Input: s = “anagram”, t = “nagaram”
Output: true


Example 2:

Input: s = “rat”, t = “car”
Output: false


Constraints:

`1 <= s.length, t.length <= 5 104*sandt` consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

题目大意:

验证变位词

频率法解题思路(推荐):

简单题

解题步骤:

N/A

注意事项:

  1. Python代码:

    1
    2
    def isAnagram2(self, s: str, t: str) -> bool:
    return collections.Counter(s) == collections.Counter(t)

算法分析:

时间复杂度为O(n),空间复杂度O(1)


排序法算法II解题思路:

Python代码:

1
2
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)

算法分析:

时间复杂度为O(nlogn),空间复杂度O(1)

Free mock interview