For equal strings, require a repeated character. Otherwise collect mismatch positions and verify that exactly two cross-match.
Complexity
O(n) time and O(1) space for a fixed alphabet.
Check whether swapping exactly two characters in one string can produce another string.
For equal strings, require a repeated character. Otherwise collect mismatch positions and verify that exactly two cross-match.
O(n) time and O(1) space for a fixed alphabet.
package main
func buddyStrings(s string, goal string) bool {
if len(s) != len(goal) {
return false
}
if s == goal {
seen := map[byte]bool{}
for index := range s {
if seen[s[index]] {
return true
}
seen[s[index]] = true
}
return false
}
mismatch := []int{}
for index := range s {
if s[index] != goal[index] {
mismatch = append(mismatch, index)
}
}
return len(mismatch) == 2 && s[mismatch[0]] == goal[mismatch[1]] && s[mismatch[1]] == goal[mismatch[0]]
}
class Solution:
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal): return False
if s == goal: return len(set(s)) < len(s)
mismatch = [index for index in range(len(s)) if s[index] != goal[index]]
return len(mismatch) == 2 and s[mismatch[0]] == goal[mismatch[1]] and s[mismatch[1]] == goal[mismatch[0]]
function buddyStrings(s: string, goal: string): boolean {
if (s.length !== goal.length) return false;
if (s === goal) return new Set(s).size < s.length;
const mismatch: number[] = [];
for (let index = 0; index < s.length; index += 1) if (s[index] !== goal[index]) mismatch.push(index);
return mismatch.length === 2 && s[mismatch[0]] === goal[mismatch[1]] && s[mismatch[1]] === goal[mismatch[0]];
}