Problem Link: https://leetcode.com/problems/valid-anagram/
Valid Anagram - LeetCode
Can you solve this real interview question? Valid Anagram - 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
leetcode.com
Solution 1. Hash Table (Iteration)
Time: $O(N)$
Space: $O(N)$
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
freq_s = dict()
freq_t = dict()
if len(s) != len(t):
return False
for x, y in zip(s, t):
freq_s[x] = freq_s.get(x, 0) + 1
freq_t[y] = freq_t.get(y, 0) + 1
while freq_s:
key, val = freq_s.popitem()
if not (key in freq_t) or val != freq_t[key]:
return False
return True
'Problem Solving' 카테고리의 다른 글
[Leetcode] 733. Flood Fill (0) | 2023.07.18 |
---|---|
[Leetcode] 704. Binary Search (0) | 2023.07.17 |
[Leetcode] 226. Invert Binary Tree (0) | 2023.07.13 |
[Leetcode] 125. Valid Palindrome (0) | 2023.07.12 |
[Leetcode] 121. Best Time to Buy and Sell Stock (0) | 2023.07.12 |