To make t an anagram of s, we need to match the character counts. For each character, count how many more are needed in t to match s. The sum of positive differences gives the minimum steps.
#include<string>#include<vector>usingnamespace std;
classSolution {
public:int minSteps(string s, string t) {
vector<int> cnt(26, 0);
for (char c : s) cnt[c -'a']++;
for (char c : t) cnt[c -'a']--;
int res =0;
for (int x : cnt) if (x >0) res += x;
return res;
}
};
classSolution {
publicintminSteps(String s, String t) {
int[] cnt =newint[26];
for (char c : s.toCharArray()) cnt[c -'a']++;
for (char c : t.toCharArray()) cnt[c -'a']--;
int res = 0;
for (int x : cnt) if (x > 0) res += x;
return res;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funminSteps(s: String, t: String): Int {
val cnt = IntArray(26)
for (c in s) cnt[c - 'a']++for (c in t) cnt[c - 'a']--var res = 0for (x in cnt) if (x > 0) res += x
return res
}
}
1
2
3
4
5
classSolution:
defminSteps(self, s: str, t: str) -> int:
from collections import Counter
cs, ct = Counter(s), Counter(t)
return sum(max(cs[c] - ct[c], 0) for c in cs)
1
2
3
4
5
6
7
8
9
10
use std::collections::HashMap;
impl Solution {
pubfnmin_steps(s: String, t: String) -> i32 {
letmut cs = [0; 26];
letmut ct = [0; 26];
for c in s.chars() { cs[(c asu8-b'a') asusize] +=1; }
for c in t.chars() { ct[(c asu8-b'a') asusize] +=1; }
(0..26).map(|i| (cs[i] - ct[i]).max(0)).sum()
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
minSteps(s: string, t: string):number {
constcs= Array(26).fill(0), ct= Array(26).fill(0);
for (constcofs) cs[c.charCodeAt(0) -97]++;
for (constcoft) ct[c.charCodeAt(0) -97]--;
letres=0;
for (leti=0; i<26; ++i) if (cs[i] +ct[i] >0) res+=cs[i] +ct[i];
returnres;
}
}