0859. Buddy Strings

859. Buddy Strings #

Problem #

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.

Problem Summary #

Given two strings s and goal, return true as long as we can obtain a result equal to goal by swapping two letters in s; otherwise, return false.

Swapping letters is defined as: take two indices i and j (0-indexed) such that i != j, and then swap the characters at s[i] and s[j].

For example, swapping the elements at index 0 and index 2 in “abcd” can generate “cbad”.

Solution Approach #

Compare in two cases:

  • If s equals goal, return true if there are duplicate elements in s; otherwise return false
  • If s does not equal goal, there are two characters at different indices in s that are respectively equal to the characters at the corresponding indices in goal

Code #


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]
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文