LeetCode每日一题(2531. Make Number of Distinct Characters Equal)

这篇博客讨论了如何解决LeetCode中的一个问题,即通过一次字符交换使得两个字符串的唯一字符数量相等。文章给出了几个示例,解释了在不同情况下是否可能达到目标,并提出了统计每个字符串中各字符出现次数然后进行交换的思路。
摘要由CSDN通过智能技术生成

You are given two 0-indexed strings word1 and word2.

A move consists of choosing two indices i and j such that 0 <= i < word1.length and 0 <= j < word2.length and swapping word1[i] with word2[j].

Return true if it is possible to get the number of distinct characters in word1 and word2 to be equal with exactly one move. Return false otherwise.

Example 1:

Input: word1 = “ac”, word2 = “b”
Output: false

Explanation: Any pair of swaps would yield two distinct characters in the first string, and one in the second string.

Example 2:

Input: word1 = “abcc”, word2 = “aab”
Output: true

Explanation: We swap index 2 of the first string with index 0 of the second string. The resulting strings are word1 = “abac” and word2 = “cab”, which both have 3 distinct characters.

Example 3:

Input: word1 = “abcde”, word2 = “fghij”
Output: true

Explanation: Both resulting strings will have 5 distinct characters, regardless of which indices we swap.

Constraints:

  • 1 <= word1.length, word2.length <= 105
  • word1 and word2 consist of only lowercase English letters.

速度不怎么理想,但是好在思路比较直观, 就是分别把 word1 和 word2 中的字母频次统计出来, 然后把 word1 中的 a-z 与 word2 中的 a-z 进行交换



use std::collections::HashMap;

impl Solution {
   
    pub fn is_it_possible(word1: String, word2: String) -> bool {
   
        let mut m1 = word1.chars()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值