Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created January 13, 2019 06:23
Show Gist options
  • Save ttsugriy/ef261e21dc6ce2d5df6278aa1731af51 to your computer and use it in GitHub Desktop.
Save ttsugriy/ef261e21dc6ce2d5df6278aa1731af51 to your computer and use it in GitHub Desktop.
class Solution {
public:
bool buddyStrings(const string& A, const string& B) {
if (A.size() != B.size()) return false;
vector<int> mismatches;
bool has_duplicates = false;
int letters = 0;
for (int i = 0; i < A.size(); ++i) {
int idx = 1 << (A[i] - 'a');
has_duplicates |= letters & idx;
letters |= idx;
if (A[i] != B[i]) {
if (mismatches.size() >= 2) return false;
mismatches.push_back(i);
}
}
if (mismatches.empty() && has_duplicates) return true;
if (mismatches.size() < 2 || mismatches.size() > 2) return false;
return A[mismatches[0]] == B[mismatches[1]] && A[mismatches[1]] == B[mismatches[0]];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment