-
Medium
-
You are given two strings of the same length
s
andt
. In one step you can choose any character oft
and replace it with another character.Return the minimum number of steps to make
t
an anagram ofs
.An Anagram of a string is a string that contains the same characters with a different (or the same) ordering.
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
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;
}