Sunday, August 2, 2020

859. Buddy Strings -----------E

Q:

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

 

Constraints:

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

A:


class Solution {
public:
    bool buddyStrings(string A, string B) {
        vector<int> V;
        if(A.length() != B.length())
            return false;
        for(int i=0;i <A.length();++i)
            if(A[i] != B[i])
                V.push_back(i);
        if(V.size()==2){ // if two different place
            int a = V[0], b = V[1];
            return (A[a]==B[b]) &&  (A[b] == B[a]);
        }else if(V.size()==0){ // all same. check if A contains same character
            vector<bool> C(26,false);
            for(char ch : A){
                if(C[ch-'a'])
                    return true;
                C[ch-'a'] = true;
            }
        }
        return false;
    }
};



一开始忘了测试 V.size()==1的情况, 肏了

No comments:

Post a Comment