KK's blog

每天积累多一些

0%

LeetCode Buddy Strings

LeetCode



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.


Constraints:
1 <= s.length, goal.length <= 2 * 10<sup>4</sup>
* s and goal consist of lowercase letters.

题目大意:

给定两字符串,交换一次使得他们相等

解题思路:

三种情况: 长度不等,完全相等(若至少有一个重复,即满足题意),两次不同

解题步骤:

N/A

注意事项:

  1. 三种情况: 长度不等,完全相等,两次不同

Python代码:

1
2
3
4
5
6
7
def buddyStrings(self, s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
if s == goal and len(set(s)) < len(goal): # any dups
return True
diff = [(a, b) for a, b in zip(s, goal) if a != b]
return True if len(diff) == 2 and diff[0] == diff[1][::-1] else False

算法分析:

时间复杂度为O(n),空间复杂度O(1)

Free mock interview