码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 859. Buddy Strings

时间:2018-06-24 13:04:59      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:class   put   char   cout   str   let   aaa   aaaaa   int   

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

标签:class   put   char   cout   str   let   aaa   aaaaa   int   

原文地址:https://www.cnblogs.com/pk28/p/9219964.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!