nathanwailes

LeetCode 242 - Valid Anagram - 2023.03.31 solution from ChatGPT

Mar 31st, 2023
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. class Solution:
  2.     def isAnagram(self, s: str, t: str) -> bool:
  3.         if len(s) != len(t):
  4.             return False
  5.        
  6.         # create a dictionary to keep track of the frequency of each character in s
  7.         freq = {}
  8.         for char in s:
  9.             if char in freq:
  10.                 freq[char] += 1
  11.             else:
  12.                 freq[char] = 1
  13.        
  14.         # iterate through t and decrement the frequency of each character
  15.         # if a character is not in freq, or its frequency becomes negative, return False
  16.         for char in t:
  17.             if char not in freq or freq[char] == 0:
  18.                 return False
  19.             freq[char] -= 1
  20.        
  21.         return True
Advertisement
Add Comment
Please, Sign In to add comment