Algorithm
- Initialize an array
countof size26, - Set all indices point to
0initially - Iterate over the integer from
0to the last index insort, for each indexi:- Increment the frequency of character
t[i]in the arraycount. - Decerement the frequency of character
s[i]in the arraycount.
- Increment the frequency of character
- Initialize the variable
ansto0 - Iterate over the integers from
0to25, and for each positive frequency difference, add it to the variableans. - Return
ans.
Java
public int minSteps(String s, String t) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[t.charAt(i) - 'a']++;
count[s.charAt(i) - 'a']--;
}
int ans = 0;
for (int i = 0; i < 26; i++) {
ans += Math.max(0, count[i]);
}
return ans;
}
Python
def minSteps(self, s: str, t: str) -> int:
cnt1 = Counter(s)
cnt2 = Counter(t)
res = 0
for c in ascii_lowercase:
if cnt2[c] > cnt1[c]:
res += cnt2[c] - cnt1[c]
return res
Leave a comment