leetcode 859 Buddy Strings

python:

class Solution:
    def buddyStrings(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: bool
        """

        if A == B:
            return len(set(A)) != len(A)
        if len(A) != len(B) or A == B:
            return False
        flag = True
        a = list(A)
        for i in range(len(A)):
            if A[i] != B[i]:
                if flag:
                    flag = False
                    j = i
                else:
                    a[i], a[j] = a[j], a[i]
                    C = ''.join(k for k in a)
                    print(C)
                    return C == B
        return False

c++:

class Solution {
public:
    bool buddyStrings(string A, string B) {
        if (unordered_set<char> (A.begin(), A.end()).size() != A.length() && A == B)
            return true;
        if (A == B || A.length()!=B.length())
            return false;
        
        vector<int> index;
        int flag = 2;
            
        for (int i=0; i<A.length(); i++){
            if (A[i] != B[i]){
                index.push_back(i);
                flag--;
            }
        }
            return flag == 0 && (A[index[0]] == B[index[1]] && 
                                B[index[0]] == A[index[1]]);
    }
};

猜你喜欢

转载自blog.csdn.net/MRxjh/article/details/82662241