LeetCode75——Day22

文章目录

一、题目

1657. Determine if Two Strings Are Close

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.

Example 1:

Input: word1 = "abc", word2 = "bca"

Output: true

Explanation: You can attain word2 from word1 in 2 operations.

Apply Operation 1: "abc" -> "acb"

Apply Operation 1: "acb" -> "bca"

Example 2:

Input: word1 = "a", word2 = "aa"

Output: false

Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations.

Example 3:

Input: word1 = "cabbba", word2 = "abbccc"

Output: true

Explanation: You can attain word2 from word1 in 3 operations.

Apply Operation 1: "cabbba" -> "caabbb"

Apply Operation 2: "caabbb" -> "baaccc"

Apply Operation 2: "baaccc" -> "abbccc"

Constraints:

1 <= word1.length, word2.length <= 105

word1 and word2 contain only lowercase English letters.

题目来源: leetcode

二、题解

当两个字符串,所拥有的共同字符类型完全相同,且字母出现数目以及出现该数目的个数完全相同时,这两个字符串是close的。

cpp 复制代码
class Solution {
public:
    bool closeStrings(string word1, string word2) {
        int n1 = word1.length();
        int n2 = word2.length();
        vector<int> map1(26,0);
        vector<int> map2(26,0);
        vector<int> times(max(n1,n2) + 1,0);
        for(int i = 0;i < n1;i++) map1[word1[i] - 'a']++;
        for(int i = 0;i < n2;i++) map2[word2[i] - 'a']++;
        //如果有字母不在交集中
        for(int i = 0;i < 26;i++){
            if((map1[i] == 0 && map2[i] != 0) || (map1[i] != 0 && map2[i] == 0)) return false;
        }
        //统计出现次数的个数
        for(int i = 0;i < 26;i++){
            if(map1[i] != 0) {
                times[map1[i]]++;   
            }
        }
        for(int i = 0;i < 26;i++){
            if(map2[i] != 0) times[map2[i]]--;
            if(times[map2[i]] < 0) return false;
        }
        return true;
    }
};
相关推荐
什么半岛铁盒1 小时前
C++11 多线程与并发编程
c语言·开发语言·c++
WHS-_-20223 小时前
A Density Clustering-Based CFAR Algorithm for Ship Detection in SAR Images
算法·5g
Mr_WangAndy4 小时前
C++设计模式_结构型模式_组合模式Composite(树形模式)
c++·设计模式·组合模式
Miraitowa_cheems6 小时前
LeetCode算法日记 - Day 68: 猜数字大小II、矩阵中的最长递增路径
数据结构·算法·leetcode·职场和发展·贪心算法·矩阵·深度优先
希赛网6 小时前
软考软件设计师常考知识点:(三)数据结构
数据结构·二叉树·字符串·软考·软件设计师·线性表
灵感__idea8 小时前
Hello 算法:让前端人真正理解算法
前端·javascript·算法
学习2年半8 小时前
小米笔试题:一元一次方程求解
算法
MATLAB代码顾问8 小时前
MATLAB绘制多种混沌系统
人工智能·算法·matlab
极客BIM工作室9 小时前
演化搜索与群集智能:五种经典算法探秘
人工智能·算法·机器学习
qq_574656259 小时前
java-代码随想录第66天|Floyd 算法、A * 算法精讲 (A star算法)
java·算法·leetcode·图论