nathanwailes

LeetCode 242 - Valid Anagram - 2023.09.29 solution

Sep 29th, 2023
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.78 KB | None | 0 0
  1. class Solution:
  2.     def isAnagram(self, s: str, t: str) -> bool:
  3.         """ Solution: We can use a dict to keep track of the counts of each
  4.        character in each string, and then iterate through the alphabet to
  5.        check each character to make sure the count is the same.
  6.        """
  7.         s_count = dict()
  8.         t_count = dict()
  9.  
  10.         for c in s:
  11.             if c in s_count:
  12.                 s_count[c] += 1
  13.             else:
  14.                 s_count[c] = 1
  15.        
  16.         for c in t:
  17.             if c in t_count:
  18.                 t_count[c] += 1
  19.             else:
  20.                 t_count[c] = 1
  21.            
  22.         for c in 'abcdefghijklmnopqrstuvwxyz':
  23.             if s_count.get(c) != t_count.get(c):
  24.                 return False
  25.         return True
Advertisement
Add Comment
Please, Sign In to add comment