【036】2531【参考】. 使字符串总不同字符的数目相等[哈希表 + 暴力遍历]

给你两个下标从 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();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值