LeetCode intimate string

Disclaimer: This article is a blogger original articles, blog address: https: //blog.csdn.net/qq_41855420, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_41855420/article/details/91045892

Given two strings A and B composed of lowercase letters, as long as we can obtain results equivalent to B via A in two letters exchange, it returns true; otherwise returns false.

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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

prompt:

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

think road \ Color {blue} thinking analysis: This question is quite simple,
as long as we seize the definition of a string of intimate - A B \ Color {red} The results obtained with B equal to A via the exchange of two letters! For A, B itself two strings are equal, then we can select two exchange character the same character will not affect the switching, so when A == B, we need to determine A (or B), if the same character of.

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];
        }
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_41855420/article/details/91045892