2186.制造字母异位词的最小步骤数-ii
小于 1 分钟
2186.制造字母异位词的最小步骤数-ii
import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
public class MiniSteps {
public static void main(String[] args) {
String str1 = "uxfgkiykldv";
String str2 = "ucyhpacdgmughvjtrmgf";
int res = returnStep(str1, str2);
System.out.println("最小步骤数为:" + res);
}
public static int returnStep(String s1, String s2) {
String m = "";
if (s2.length() >= s1.length()) { // s1始终为最长字符串,方便组成最长哈希表
m = s1;
s1 = s2;
s2 = m;
}
// 生成一个哈希表,值为出现次数,s1中出现+1,s2中出现-1,统计最终绝对值
HashMap<Character, Integer> map = new HashMap<>();
// 遍历字符串s1
for (int i = 0; i < s1.length(); i++) { // 生成哈希表
// map.put(s1.charAt(i), map.getOrDefault(s1.charAt(i), 0) + 1);
if (map.get(s1.charAt(i)) == null) {
map.put(s1.charAt(i), 1);
} else {
map.put(s1.charAt(i), map.get(s1.charAt(i)) + 1);
}
}
List<Character> s2Diff = new ArrayList<Character>();
// 遍历s2
for (int i = 0; i < s2.length(); i++) {
if (map.get(s2.charAt(i)) == null) { // s1生成的哈希表中不存在该key时,存入
map.put(s2.charAt(i), 1);
s2Diff.add(s2.charAt(i));
} else {
// s2塞入哈希表中的,值需+1
if (s2Diff.contains(s2.charAt(i))) {
map.put(s2.charAt(i), map.get(s2.charAt(i)) + 1);
} else {
map.put(s2.charAt(i), map.get(s2.charAt(i)) - 1);
}
}
}
// 统计绝对值之和
int total = map.values().stream().mapToInt(i -> Math.abs(i)).sum();
return total;
}
}
Loading...
