LeetCode 亲密字符串

版权声明:本文为博主原创文章,博客地址:https://blog.csdn.net/qq_41855420,未经博主允许不得转载。 https://blog.csdn.net/qq_41855420/article/details/91045892

给定两个由小写字母构成的字符串 A 和 B ,只要我们可以通过交换 A 中的两个字母得到与 B 相等的结果,就返回 true ;否则返回 false 。

示例 1:

输入: A = "ab", B = "ba"
输出: true

示例 2:

输入: A = "ab", B = "ab"
输出: false

示例 3:

输入: A = "aa", B = "aa"
输出: true

示例 4:

输入: A = "aaaaaaabc", B = "aaaaaaacb"
输出: true

示例 5:

输入: A = "", B = "aa"
输出: false

提示:

0 <= A.length <= 20000
0 <= B.length <= 20000
A 和 B 仅由小写字母构成。

\color{blue}思路分析: 这道题还是比较简单的,
我们只要抓住亲密字符串的定义—— A B \color{red}通过交换 A 中的两个字母得到与 B 相等的结果! ,对于A、B两个字符串本身就相等,则我们交换字符只能选择两个相同的字符交换才不会影响,因此当A == B,我们需要判断A(或B)中是否有相同的字符。

class Solution {
public:
    bool buddyStrings(string A, string B) {
        if (A.size() != B.size()){
            return false;
        }
        //diffChCount记录A、B串中不相同的字符数
        //indexOne、indexTwo分别记录前两次不相同的下标
        int diffChCount = 0, indexOne, indexTwo;
        //同时扫描A、B串
        for (int i = A.size() - 1; i >= 0; --i){
            if (A[i] != B[i]){
                diffChCount += 1;
                if (diffChCount == 1){
                    indexOne = i;
                }
                else if (diffChCount == 2){
                    indexTwo = i;
                }
                else{//超过2次则不能是亲密字符串
                    return false;
                }
            }
        }
        if (diffChCount == 0){
            //当A == B,我们需要判断A(或B)中是否有相同的字符。
            vector<int> chCount(26, 0);//统计各个字符出现的次数
            for (int i = A.size() - 1; i >= 0; --i){
                if (++chCount[A[i] - 'a'] > 1){//出现相同的字符
                    return true;
                }
            }
            return false;
        }
        else{
            //通过交换能使A == B
            return diffChCount == 2 && A[indexOne] == B[indexTwo] && A[indexTwo] == B[indexOne];
        }
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41855420/article/details/91045892