Skip to content

Latest commit

 

History

History
61 lines (48 loc) · 1.44 KB

1347.-minimum-number-of-steps-to-make-two-strings-anagram.md

File metadata and controls

61 lines (48 loc) · 1.44 KB

1347. Minimum Number of Steps to Make Two Strings Anagram

  • Medium

  • You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character.

    Return the minimum number of steps to make t an anagram of s.

    An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.

Analysis

Create an array / dictionary to record the number of appearance of each letter, then calculate the difference. Then divide by two and we would have our answer.

class Solution:
    def minSteps(self, s: str, t: str) -> int:
        count=[0]*26
        for i in s:
            count[ord(i)-ord('a')]+=1
        for j in t:
            count[ord(j)-ord('a')]-=1
        ans=0
        for m in count:
            
            ans+=abs(m)
        return ans//2

Solution C

int minSteps(char * s, char * t){
    int count[26];
    for (int i=0; i<26;i++)
    {
        count[i]=0;
    }
    int len=strlen(s);
    for (int i=0; i<len;i++)
    {
        count[(int)s[i]-(int)'a']++;
    }
    for (int i=0; i<len;i++)
    {
        count[(int)t[i]-(int)'a']--;
    }
    int ans=0;
    for (int i=0; i<26;i++)
    {
        ans+=abs(count[i]);
    }
    ans=ans/2;
    return ans;
}