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

猜你喜欢

转载自www.cnblogs.com/pk28/p/9219964.html