> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/859.buddy_strings.md).

# 859.Buddy Strings

**859.Buddy Strings**

难度:Easy

> 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
 

Note:

0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.
```

判断两个字串是否相等，如果相等，看看有没有重复的字母，有则可以交换，没有则返回false。 两个字串不相等，则比较不相等的位置，是不是刚好有两个，并判断两个是不是交换之后相等。

```
class Solution {
public:
    bool buddyStrings(string A, string B) {
        if(A.length() != B.length() ) return false;
        if(A==B) 
        {
            vector<int>alpha(26,0);
            for(auto c:A)
            {
                if(++alpha[c-'a'] >1) return true;
            }
            return false;
        }
        int count=0;
        vector<int> index;
        for(int i=0;i<A.length();i++)
        {
            if(A[i] !=B[i]) 
            {
                count++;
                index.push_back(i);
            }
        }
        if(count !=2) return false;
        //cout<< index[0] <<" "<<index[1]<<endl;
        if(A[index[0]] == B[index[1]] && A[index[1]] == B[index[0]]) return true;
        return false;
    }
};
```

> 执行用时 :8 ms, 在所有 C++ 提交中击败了81.11%的用户\
> 内存消耗 :9.1 MB, 在所有 C++ 提交中击败了49.58%的用户
