设两个字符串分别为 s 和 goal,其中 s[i] 表示 s 的第 i 个字符,其中 goal}[i] 表示 goal 的第 i 个字符。如果 s[i] = \textit{goal}[i],我们就说 i 是匹配的,否则称 i 是不匹配的。亲密字符串定义为:需要交换 s 中的第 i 个字符 s[i] 与 s 中第 j 个字符且满足 i \neq j,交换后 s 与 goal 相等。亲密字符串的两个字符串需要交换一次索引不相等的两个字符后相等。
如果满足交换 s[i] 和 s[j] 后两个字符串相等,那么需要满足以下几个条件使得 s 和 goal 为亲密字符串:
classSolution: defbuddyStrings(self, s: str, goal: str) -> bool: iflen(s) != len(goal): returnFalse if s == goal: iflen(set(s)) < len(goal): returnTrue else: returnFalse diff = [(a, b) for a, b inzip(s, goal) if a != b] returnlen(diff) == 2and diff[0][0] == diff[1][1] and diff[0][1] == diff[1][0]
if s == goal { seen := [26]bool{} for _, ch := range s { if seen[ch-'a'] { returntrue } seen[ch-'a'] = true } returnfalse }
first, second := -1, -1 for i := range s { if s[i] != goal[i] { if first == -1 { first = i } elseif second == -1 { second = i } else { returnfalse } } } return second != -1 && s[first] == goal[second] && s[second] == goal[first] }
var buddyStrings = function(s, goal) { if (s.length != goal.length) { returnfalse; } if (s === goal) { const count = newArray(26).fill(0); for (let i = 0; i < s.length; i++) { count[s[i].charCodeAt() - 'a'.charCodeAt()]++; if (count[s[i].charCodeAt() - 'a'.charCodeAt()] > 1) { returntrue; } } returnfalse; } else { let first = -1, second = -1; for (let i = 0; i < s.length; i++) { if (s[i] !== goal[i]) { if (first === -1) first = i; elseif (second === -1) second = i; else returnfalse; } }