Files
2021-11-26 00:06:25 -08:00

87 lines
2.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [859. Buddy Strings](https://leetcode.com/problems/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[0] = 'a' and s[1] = '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[0] = 'a' and s[1] = 'b', which results in "ba" != goal.
**Example 3**:
Input: s = "aa", goal = "aa"
Output: true
Explanation: You can swap s[0] = 'a' and s[1] = '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 中的两个字母得到与 goal 相等的结果,就返回 true否则返回 false 。
交换字母的定义是:取两个下标 i 和 j (下标从 0 开始)且满足 i != j ,接着交换 s[i] 和 s[j] 处的字符。
例如,在 "abcd" 中交换下标 0 和下标 2 的元素可以生成 "cbad" 。
## 解题思路
分为两种情况进行比较:
- s 等于 goal, s 中有重复元素就返回 true,否则返回 false
- s 不等于 goal, s 中有两个下标不同的字符与 goal 中对应下标的字符分别相等
## 代码
```go
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]
}
```