Given two strings
Bof lowercase letters, return
trueif you can swap two letters in
Aso the result is equal to
B, otherwise, return
Swapping letters is defined as taking two indices
j(0-indexed) such that
i != jand swapping the characters at
A[j]. For example, swapping at indices
0 <= A.length <= 20000
0 <= B.length <= 20000
Bconsist of lowercase letters.
- Level: Easy
- Acceptance: 29.5%
For this problem, one of the challenging parts was finding all the possible cases of success and failure for the algorithm. After some trial and error, it can be boiled down to these 3:
- If both strings are of unequal length, no amounts of swapping will make them equal. Hence, return false.
- If both strings are equal, check to see if there is a duplication in one of the letters. If so, you can swap them together as swapping two characters within the string is a must. And in doing so, will still yield the same string and return true. I used a set to keep track of unique characters.
- If both strings are unequal to each other, loop through them and find character pairs from A and B that are not the same and add them to an array. The strings are only “buddy strings” and true if there are exactly 4 characters in the array and the concatenation of the third and first character(from A) is the same as the concatenation of the second and last character(from B). This simulates the swap of just 2 characters in A.
All other cases will result in false.