leetcode859 C++ 12ms 亲密字符串

class Solution {
public:
    bool buddyStrings(string A, string B) {
        if(A.empty() || B.empty()){
        return false;
    }
    if(A.size() != B.size()){
        return false;
    }
    vector<int> index;
    set<char> seen;
    bool res1=false;

    for(int i=0; i<A.size(); i++){
        if(seen.count(A[i])){
            res1 = true;
        }
        else{
            seen.insert(A[i]);
        }

        if(A[i] != B[i]){
            index.push_back(i);
        }
    }


    if(index.empty()){
        return res1;
    }
    else{
        if(index.size() != 2){
            return false;
        }
        return (A[index[0]] == B[index[1]] && A[index[1]] == B[index[0]]);
    }
    }
};
原文地址:https://www.cnblogs.com/theodoric008/p/9378253.html