LeetCode 题解工作台
相似度为 K 的字符串
对于某些非负整数 k ,如果交换 s1 中两个字母的位置恰好 k 次,能够使结果字符串等于 s2 ,则认为字符串 s1 和 s2 的 相似度为 k 。 给你两个字母异位词 s1 和 s2 ,返回 s1 和 s2 的相似度 k 的最小值。 示例 1: 输入: s1 = "ab", s2 = "ba" …
3
题型
4
代码语言
3
相关题
当前训练重点
困难 · 图·搜索
答案摘要
本题实际上是一类经典的问题:求解最小操作次数。从一个初始状态 ,经过最少 次状态转换,变成目标状态 。字符串长度不超过 ,我们考虑使用 BFS 搜索来求解。 首先将初始状态 入队,用哈希表 `vis` 记录所有访问过的状态。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路
题目描述
对于某些非负整数 k ,如果交换 s1 中两个字母的位置恰好 k 次,能够使结果字符串等于 s2 ,则认为字符串 s1 和 s2 的 相似度为 k 。
给你两个字母异位词 s1 和 s2 ,返回 s1 和 s2 的相似度 k 的最小值。
示例 1:
输入:s1 = "ab", s2 = "ba" 输出:1
示例 2:
输入:s1 = "abc", s2 = "bca" 输出:2
提示:
1 <= s1.length <= 20s2.length == s1.lengths1和s2只包含集合{'a', 'b', 'c', 'd', 'e', 'f'}中的小写字母s2是s1的一个字母异位词
解题思路
方法一:BFS
本题实际上是一类经典的问题:求解最小操作次数。从一个初始状态 ,经过最少 次状态转换,变成目标状态 。字符串长度不超过 ,我们考虑使用 BFS 搜索来求解。
首先将初始状态 入队,用哈希表 vis 记录所有访问过的状态。
接下来每一轮,都是将队列中的所有状态转换到下一个状态,当遇到目标状态 时,当前状态转换的轮数就是答案。
我们发现,题目的重点在于如何进行状态转换。对于本题,转换操作就是交换一个字符串中两个位置的字符。如果当前字符串 与 不相等,那么我们应该在 中找到一个位置 ,满足 并且 ,然后交换 和 。这样可以使得状态最接近于目标状态。这里的状态转换可以参考以下代码中的 next() 函数。
复杂度分析:BFS 剪枝不讨论时空复杂度。
class Solution:
def kSimilarity(self, s1: str, s2: str) -> int:
def next(s):
i = 0
while s[i] == s2[i]:
i += 1
res = []
for j in range(i + 1, n):
if s[j] == s2[i] and s[j] != s2[j]:
res.append(s2[: i + 1] + s[i + 1 : j] + s[i] + s[j + 1 :])
return res
q = deque([s1])
vis = {s1}
ans, n = 0, len(s1)
while 1:
for _ in range(len(q)):
s = q.popleft()
if s == s2:
return ans
for nxt in next(s):
if nxt not in vis:
vis.add(nxt)
q.append(nxt)
ans += 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates an understanding of BFS for finding the shortest path in a graph.
- question_mark
Candidate applies optimization techniques using hash tables to avoid redundant state processing.
- question_mark
Candidate effectively uses string manipulation techniques to reduce unnecessary swaps.
常见陷阱
外企场景- error
Overlooking the importance of BFS for level-based state exploration could lead to an inefficient solution.
- error
Failing to use a hash table to track visited states will result in redundant calculations and higher time complexity.
- error
Not considering early termination when the target string is reached can lead to unnecessary calculations and slow performance.
进阶变体
外企场景- arrow_right_alt
What if the two strings are already equal? In this case, the solution should immediately return 0 without further computation.
- arrow_right_alt
Consider the case where only one swap is needed: this will test if the algorithm handles minimal cases effectively.
- arrow_right_alt
What if there are repeated characters? Ensure that the algorithm handles string transformations correctly, even when characters appear multiple times.