LeetCode 题解工作台

相似度为 K 的字符串

对于某些非负整数 k ,如果交换 s1 中两个字母的位置恰好 k 次,能够使结果字符串等于 s2 ,则认为字符串 s1 和 s2 的 相似度为 k 。 给你两个字母异位词 s1 和 s2 ,返回 s1 和 s2 的相似度 k 的最小值。 示例 1: 输入: s1 = "ab", s2 = "ba" …

category

3

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

困难 · 图·搜索

bolt

答案摘要

本题实际上是一类经典的问题:求解最小操作次数。从一个初始状态 ,经过最少 次状态转换,变成目标状态 。字符串长度不超过 ,我们考虑使用 BFS 搜索来求解。 首先将初始状态 入队,用哈希表 `vis` 记录所有访问过的状态。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 图·搜索 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

对于某些非负整数 k ,如果交换 s1 中两个字母的位置恰好 k 次,能够使结果字符串等于 s2 ,则认为字符串 s1s2 相似度为 k

给你两个字母异位词 s1s2 ,返回 s1s2 的相似度 k 的最小值。

 

示例 1:

输入:s1 = "ab", s2 = "ba"
输出:1

示例 2:

输入:s1 = "abc", s2 = "bca"
输出:2

 

提示:

  • 1 <= s1.length <= 20
  • s2.length == s1.length
  • s1 和 s2  只包含集合 {'a', 'b', 'c', 'd', 'e', 'f'} 中的小写字母
  • s2s1 的一个字母异位词
lightbulb

解题思路

方法一:BFS

本题实际上是一类经典的问题:求解最小操作次数。从一个初始状态 s1s_1,经过最少 kk 次状态转换,变成目标状态 s2s_2。字符串长度不超过 2020,我们考虑使用 BFS 搜索来求解。

首先将初始状态 s1s_1 入队,用哈希表 vis 记录所有访问过的状态。

接下来每一轮,都是将队列中的所有状态转换到下一个状态,当遇到目标状态 s2s_2 时,当前状态转换的轮数就是答案。

我们发现,题目的重点在于如何进行状态转换。对于本题,转换操作就是交换一个字符串中两个位置的字符。如果当前字符串 s[i]s[i]s2[i]s_2[i] 不相等,那么我们应该在 ss 中找到一个位置 jj,满足 s[j]=s2[i]s[j] = s_2[i] 并且 s[j]s2[j]s[j] \neq s_2[j],然后交换 s[i]s[i]s[j]s[j]。这样可以使得状态最接近于目标状态。这里的状态转换可以参考以下代码中的 next() 函数。

复杂度分析:BFS 剪枝不讨论时空复杂度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

相似度为 K 的字符串题解:图·搜索 | LeetCode #854 困难