文章

242-valid-anagram

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

Example 1:

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

Output: true

Example 2:

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

Output: false

My solution:

Use dict data structure to count the occurence of every character of s, and then minus them when they occur in t.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        visited = {}
        for char in s:
            if char in visited:
                visited[char] += 1
            else:
                visited[char] = 1
        
        for char in t:
            if char in visited:
                visited[char] -= 1

        for char in visited:
            if visited[char] != 0:
                return False
                
        return True       
        

Time Complexity: O(n) Space Complexity: O(n)

本文由作者按照 CC BY 4.0 进行授权