1657. Determine if Two Strings Are Close

LeetCode 75

内容持续更新…(始于2024年08月19日)

1.问题

Two strings are considered close if you can attain one from the other using the following operations:

Operation 1: Swap any two existing characters.
For example, abcde -> aecdb
Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character.
For example, aacabb -> bbcbaa (all a’s turn into b’s, and all b’s turn into a’s)
You can use the operations on either string as many times as necessary.

Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise.

  • 字符集:两个字符串必须包含相同的字符集。如果有一个字符串包含某个字符,而另一个没有,则无法通过任何操作将它们变成相同的字符串。

  • 字符频率:两个字符串中的每个字符出现的次数必须可以通过排列组合变得相同。例如,如果一个字符串中字符 ‘a’ 出现3次,字符 ‘b’ 出现2次,而另一个字符串中相应地出现的字符的次数也是3次和2次,那么可以通过字符交换或转换达到相同的频率分布。

  • 解决方案思路:
    长度检查:首先,两个字符串的长度必须相同,否则直接返回 false。
    字符集检查:检查两个字符串是否有相同的字符集。
    字符频率检查:检查每个字符的频率是否可以匹配,即字符频率排序后是否相同。在这里插入图片描述

2. 解题思路

方法1:

  1. 检查长度:首先检查 word1 和 word2 的长度是否相同。如果不同,直接返回 false。

  2. 统计字符频率:

  • 使用两个 HashMap 分别统计 word1 和 word2 中每个字符的出现频率。
  1. 检查字符集:
  • 将 map1 和 map2 的键集合转换为 Set 并比较,确保字符集相同。
  1. 检查频率:

将字符频率转换为数组,排序后比较两个频率数组是否相同。

3. 代码

代码1:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;

class Solution {
    public boolean closeStrings(String word1, String word2) {
        // 检查长度
        if (word1.length() != word2.length()) {
            return false;
        }

        // 统计字符频率
        Map<Character, Integer> map1 = new HashMap<>();
        Map<Character, Integer> map2 = new HashMap<>();
        
        for (char c : word1.toCharArray()) {
            map1.put(c, map1.getOrDefault(c, 0) + 1);
        }
        
        for (char c : word2.toCharArray()) {
            map2.put(c, map2.getOrDefault(c, 0) + 1);
        }

        // 检查字符集是否相同
        Set<Character> set1 = new HashSet<>(map1.keySet());
        Set<Character> set2 = new HashSet<>(map2.keySet());
        if (!set1.equals(set2)) {
            return false;
        }

        // 检查频率是否相同
        int[] freq1 = new int[map1.size()];
        int[] freq2 = new int[map2.size()];
        
        int i = 0;
        for (int freq : map1.values()) {
            freq1[i++] = freq;
        }

        i = 0;
        for (int freq : map2.values()) {
            freq2[i++] = freq;
        }

        Arrays.sort(freq1);
        Arrays.sort(freq2);
        
        return Arrays.equals(freq1, freq2);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值