leetcode 859. Buddy Strings

Posted いいえ敗者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 859. Buddy Strings相关的知识,希望对你有一定的参考价值。

Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.

Example 1:

Input: A = "ab", B = "ba"
Output: true
Example 2:

Input: A = "ab", B = "ab"
Output: false
Example 3:

Input: A = "aa", B = "aa"
Output: true
Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:

Input: A = "", B = "aa"
Output: false

题目大意:给出A,B两个字符串,问能否swap一次A串中的两个字符使得A==B

思路:直接找A中和B中不等的字符个数num,如果num==1,或者num==0且A串中有至少两个一样的字符那么就返回YES

代码写的有点乱...

class Solution {
public:
    bool buddyStrings(string A, string B) {
        string a = A;
        string b = B;
        sort(A.begin(), A.end());
        sort(B.begin(), B.end());
        if (A!=B) return false;
        int num = 0;
        map<char, char> mp;
        map<char, int> cnt;
        for (int i = 0; i < a.size(); ++i) {
            if (a[i] != b[i] && mp[a[i]] != b[i]) {
                num++;
                mp[b[i]] = a[i];
            }
            cnt[a[i]]++;
        }
        if (num == 1) return true;
        else if (num == 0) {
            for (auto x : cnt){
                //cout << x.first <<" " << x.second << endl;
                if (x.second >= 2) return true;
            }
            //cout << "no" << endl;
            return false;
        }
        return false;
    }
};

以上是关于leetcode 859. Buddy Strings的主要内容,如果未能解决你的问题,请参考以下文章

859. Buddy Strings - LeetCode

LeetCode.859-伙伴字符串(Buddy Strings)

leetcode 859. 亲密字符串(Buddy Strings)

859. 亲密字符串

859. Buddy Strings (wrong 4 times so many cases to test and consider) if else**

解题报告Leecode 859. 亲密字符串——Leecode每日一题系列