KK's blog

每天积累多一些

0%

LeetCode 242 Valid Anagram

LeetCode

<div>

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:

<pre>Input: s = "anagram", t = "nagaram" Output: true </pre>

Example 2:

<pre>Input: s = "rat", t = "car" Output: false </pre>

Constraints:

  • 1 <= s.length, t.length <= 5 * 10<sup>4</sup>
  • s and t consist of lowercase English letters.

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

</div>

题目大意:

验证变位词

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

简单题

解题步骤:

N/A

注意事项:

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