#859
Buddy Strings
pupil · 550 · lc easy +28 · verified · 33.9% accepted · 3,349 likes · top 11%
Description
Given two strings s and goal, return true if you can swap exactly two characters in s to make it equal to goal, otherwise return false.
A swap selects two distinct indices i and j (i != j) and exchanges s[i] with s[j].
- For example, swapping indices 0 and 2 in "abcd" produces "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.
Code
1
2
3