Created
January 13, 2019 06:23
-
-
Save ttsugriy/ef261e21dc6ce2d5df6278aa1731af51 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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