制造字母异位词的最小步骤数 II
难度:
标签:
题目描述
代码结果
运行时间: 166 ms, 内存: 17.3 MB
// Java Stream solution to find the minimum steps to make two strings anagrams
// by appending characters to either string
import java.util.stream.*;
public class AnagramStepsStream {
public int minSteps(String s, String t) {
// Create frequency arrays for both strings
int[] sFreq = new int[26];
int[] tFreq = new int[26];
// Populate frequency arrays using Streams
s.chars().forEach(c -> sFreq[c - 'a']++);
t.chars().forEach(c -> tFreq[c - 'a']++);
// Calculate the total number of steps needed using Streams
return IntStream.range(0, 26)
.map(i -> Math.abs(sFreq[i] - tFreq[i]))
.sum();
}
public static void main(String[] args) {
AnagramStepsStream solution = new AnagramStepsStream();
String s = "leetcode";
String t = "coats";
System.out.println(solution.minSteps(s, t)); // Output: 7
}
}
解释
方法:
本题解采用计数字典来记录两个字符串中每个字符的出现次数。首先,使用Counter对字符串s和t进行计数获取cnt1和cnt2。然后,通过将cnt1和cnt2相加,得到一个新的计数字典cnt,其中的值是字符在s和t中出现的总次数。接着,遍历cnt字典的每个键值对,计算每个字符在s中应有的数量(即总数的一半,这样才能使s和t的该字符数量相等),通过累加每个字符的差的绝对值来计算需要添加的字符总数。
时间复杂度:
O(n + m)
空间复杂度:
O(u)
代码细节讲解
🦆
题解中提到了使用Counter来计数s和t中的每个字符,为什么选择Counter而不是其他数据结构?
▷🦆
在计算`ans += abs(v - 2 * cnt1[k])`时,这里的计算逻辑是如何确保s和t互为字母异位词的?
▷🦆
为什么需要将cnt1和cnt2的计数结果相加,这样做有什么具体的目的或优势?
▷