Input: s ="**_lee_** tco _**de**_ ", t ="co _**a**_ t _**s**_ "Output: 7Explanation:
- In 2 steps, we can append the letters in"as" onto s ="leetcode", forming s ="leetcode** _as_** ".- In 5 steps, we can append the letters in"leede" onto t ="coats", forming t ="coats _**leede**_ "."leetcodeas" and "coatsleede" are now anagrams of each other.We used a total of 2+5=7 steps.It can be shown that there is no way to make them anagrams of each other with less than 7 steps.
To make s and t anagrams, we need to match the character counts. For each character, the difference in counts must be appended to one string or the other. The sum of absolute differences gives the minimum steps.
#include<string>#include<vector>usingnamespace std;
classSolution {
public:int minSteps(string s, string t) {
vector<int> cs(26, 0), ct(26, 0);
for (char c : s) cs[c -'a']++;
for (char c : t) ct[c -'a']++;
int res =0;
for (int i =0; i <26; ++i) res += abs(cs[i] - ct[i]);
return res;
}
};
classSolution {
publicintminSteps(String s, String t) {
int[] cs =newint[26], ct =newint[26];
for (char c : s.toCharArray()) cs[c -'a']++;
for (char c : t.toCharArray()) ct[c -'a']++;
int res = 0;
for (int i = 0; i < 26; ++i) res += Math.abs(cs[i]- ct[i]);
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funminSteps(s: String, t: String): Int {
val cs = IntArray(26)
val ct = IntArray(26)
for (c in s) cs[c - 'a']++for (c in t) ct[c - 'a']++var res = 0for (i in0..25) res += kotlin.math.abs(cs[i] - ct[i])
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(abs(cs[c] - ct[c]) for c in set(cs) | set(ct))
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]).abs()).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) res+= Math.abs(cs[i] -ct[i]);
returnres;
}
}