242. Valid Anagram

https://leetcode.com/problems/valid-anagram/

solution

  • hash

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False
        
        counter = {}
        for i in s:
            if i in counter:
                counter[i] += 1
            else:
                counter[i] = 1

        for j in t:
            if j in counter:
                counter[j] -= 1
            else:
                return False

        for x, y in counter.items():
            if y > 0:
                return False
        return True

时间复杂度:O(n) 空间复杂度:O(26) -> O(1)

  • hash using array 26

  • sort

follow up

125. Valid Palindrome

438. Find All Anagrams in a String

  • 滑动窗口+hash

Last updated