给你两个下标从 0 开始的字符串 word1 和 word2 。
一次 移动 由以下两个步骤组成:
选中两个下标 i 和 j ,分别满足 0 <= i < word1.length 和 0 <= j < word2.length ,
交换 word1[i] 和 word2[j] 。
如果可以通过 恰好一次 移动,使 word1 和 word2 中不同字符的数目相等,则返回 true ;否则,返回 false 。
https://leetcode.cn/problems/make-number-of-distinct-characters-equal/description/
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
*/
package com.huawei.prac;
import java.util.HashMap;
import java.util.Map;
class Solution5th {
public static void main(String[] args) {
String word1 = "abcc";
String word2 = "aab";
System.out.println(isItPossible(word1, word2));
}
/**
* 2531【参考】. 使字符串总不同字符的数目相等[哈希表 + 暴力遍历]
*
* @param word1 字符串1
* @param word2 字符串2
* @return 交换 1 个字母后不同字符的数目是否相等
*/
public static boolean isItPossible(String word1, String word2) {
Map<Character, Integer> map1 = new HashMap<>();
for (int i = 0; i < word1.length(); i++) {
map1.merge(word1.charAt(i), 1, (oldV, newV) -> ++oldV);
}
Map<Character, Integer> map2 = new HashMap<>();
for (int i = 0; i < word2.length(); i++) {
map2.merge(word2.charAt(i), 1, (oldV, newV) -> ++oldV);
}
for (Map.Entry<Character, Integer> entry1 : map1.entrySet()) {
for (Map.Entry<Character, Integer> entry2 : map2.entrySet()) {
if (isSatisfied(map1, map2, entry1.getKey(), entry2.getKey())) {
return true;
}
}
}
return false;
}
private static boolean isSatisfied(Map<Character, Integer> map1, Map<Character, Integer> map2, Character key1,
Character key2) {
Map<Character, Integer> mapTmp2 = new HashMap<>(map2);
Map<Character, Integer> mapTmp1 = new HashMap<>(map1);
mapTmp1.computeIfPresent(key1, (key, oldV) -> oldV - 1 == 0 ? null : --oldV);
mapTmp1.merge(key2, 1, (oldV, val) -> ++oldV);
mapTmp2.computeIfPresent(key2, (key, oldV) -> oldV - 1 == 0 ? null : --oldV);
mapTmp2.merge(key1, 1, (oldV, val) -> ++oldV);
return mapTmp1.size() == mapTmp2.size();
}
}