0859. Buddy Strings

# 859. Buddy Strings#

## 题目 #

Given two strings s and goal, return true if you can swap two letters in s so the result is equal to goal, otherwise, return false.

Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at s[i] and s[j].

For example, swapping at indices 0 and 2 in “abcd” results in “cbad”.

Example 1:

``````Input: s = "ab", goal = "ba"
Output: true
Explanation: You can swap s = 'a' and s = 'b' to get "ba", which is equal to goal.
``````

Example 2:

``````Input: s = "ab", goal = "ab"
Output: false
Explanation: The only letters you can swap are s = 'a' and s = 'b', which results in "ba" != goal.
``````

Example 3:

``````Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s = 'a' and s = 'a' to get "aa", which is equal to goal.
``````

Example 4:

``````Input: s = "aaaaaaabc", goal = "aaaaaaacb"
Output: true
``````

Constraints:

• 1 <= s.length, goal.length <= 2 * 10000
• s and goal consist of lowercase letters.

## 解题思路 #

• s 等于 goal, s 中有重复元素就返回 true,否则返回 false
• s 不等于 goal, s 中有两个下标不同的字符与 goal 中对应下标的字符分别相等

## 代码 #

``````
package leetcode

func buddyStrings(s string, goal string) bool {
if len(s) != len(goal) || len(s) <= 1 {
return false
}
mp := make(map[byte]int)
if s == goal {
for i := 0; i < len(s); i++ {
if _, ok := mp[s[i]]; ok {
return true
}
mp[s[i]]++
}
return false
}
first, second := -1, -1
for i := 0; i < len(s); i++ {
if s[i] != goal[i] {
if first == -1 {
first = i
} else if second == -1 {
second = i
} else {
return false
}
}
}
return second != -1 && s[first] == goal[second] && s[second] == goal[first]
}
`````` Jun 22, 2022 Edit this page