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]]);
    }
    }
};
posted @ 2018-07-27 16:17  一条图图犬  阅读(380)  评论(0编辑  收藏  举报