0

I am comparing two strings and counting in how many steps one string can be an anagram of another for which I use two hashmaps each for one string. Then I compare the difference between two hash maps as count the difference. Please help on how to count such a difference!

For example,

s="leetcode"
t= "coats"

Following is my code:

 def minSteps(self, s: str, t: str) -> int:
    map_s = {}
    map_t = {}
    for i in range(len(s)):
        if s[i] not in map_s:
            map_s[s[i]] = 0
        map_s[s[i]] += 1
    for i in range(len(t)):
        if t[i] not in map_t:
            map_t[t[i]] = 0
        map_t[t[i]] += 1
    print(map_t)
    print(map_s)
    for key, val in map_s.items():
        if val != map_t[key]: 
            count += 1
    return count

When I print both hashmaps, this is what I get and the expected difference is 7 counting the difference between two.

   {'c': 1, 'o': 1, 'a': 1, 't': 1, 's': 1}
   {'l': 1, 'e': 3, 't': 1, 'c': 1, 'o': 1, 'd': 1}

Here is a similar question. Comparing two dictionaries and checking how many (key, value) pairs are equal . However, I could not find what I am looking for. Please help!

khushbu
  • 567
  • 2
  • 8
  • 24

1 Answers1

0

If you want to count things, consider using a Counter. They can also be added and subtracted, so you could do something like this:

from collections import Counter

def minSteps(s: str, t: str) -> int:
    cs = Counter(s)
    ct = Counter(t)
    diff = (cs - ct) + (ct - cs)
    return sum(diff.values())
FMc
  • 41,963
  • 13
  • 79
  • 132