There are some possible scenarios:
- The two strings have different lengths.
s == goal
: See below- diff(s, goal) = 1: False,
ab, aa
. - diff(s, goal) = 2: Check if the two different characters can be swapped.
- diff(s, goal) > 2: False
This problem has a very particular edge case: aa
and aa
. In this case, we can swap the two a
s and get the same string. The two a's
are considered as the different characters. So we can swap them and get the same string.
fun buddyStrings(s: String, goal: String): Boolean {
if (s.length != goal.length) return false
// Handle the special edge case, if there are (multiple) duplicate characters when s == goal
// s = "aa"
// goal = "aa"
if (s == goal) {
val count = IntArray(26)
for (c in s) {
count[c - 'a']++
if (count[c - 'a'] > 1) return true
}
return false
}
// Otherwise, we need to find the two different characters
var diff1: Pair<Char, Char>? = null
var diff2: Pair<Char, Char>? = null
for (i in 0 until s.length) {
if (s[i] != goal[i]) {
if (diff1 == null) diff1 = s[i] to goal[i]
else if (diff2 == null) diff2 = s[i] to goal[i]
else {
// More than 2 differences
return false
}
}
}
if (diff1 != null && diff2 != null) {
// Check if we can swap the two different characters
return diff1.first == diff2.second && diff1.second == diff2.first
} else {
// Less than 2 differences
return false
}
}