LeetCode 题解工作台
使三个字符串相等
给你三个字符串 s1 、 s2 和 s3 。 你可以根据需要对这三个字符串执行以下操作 任意次数 。 在每次操作中,你可以选择其中一个长度至少为 2 的字符串 并删除其 最右位置上 的字符。 如果存在某种方法能够使这三个字符串相等,请返回使它们相等所需的 最小 操作次数;否则,返回 -1 。 示例 …
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
根据题目描述,我们知道,如果删除字符后的三个字符串相等,那么它们存在一个长度大于 的公共前缀。因此,我们可以枚举公共前缀的位置 ,如果当前下标 对应的三个字符不完全相等,那么公共前缀长度为 ,此时,我们判断 是否为 ,若是,返回 ,否则返回 $s - 3 \times i$,其中 为三个字符串的长度和。 时间复杂度 ,其中 为三个字符串的最小长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你三个字符串 s1、s2 和 s3。 你可以根据需要对这三个字符串执行以下操作 任意次数 。
在每次操作中,你可以选择其中一个长度至少为 2 的字符串 并删除其 最右位置上 的字符。
如果存在某种方法能够使这三个字符串相等,请返回使它们相等所需的 最小 操作次数;否则,返回 -1。
示例 1:
输入:s1 = "abc",s2 = "abb",s3 = "ab" 输出:2 解释:对 s1 和 s2 进行一次操作后,可以得到三个相等的字符串。 可以证明,不可能用少于两次操作使它们相等。
示例 2:
输入:s1 = "dac",s2 = "bac",s3 = "cac" 输出:-1 解释:因为 s1 和 s2 的最左位置上的字母不相等,所以无论进行多少次操作,它们都不可能相等。因此答案是 -1 。
提示:
1 <= s1.length, s2.length, s3.length <= 100s1、s2和s3仅由小写英文字母组成。
解题思路
方法一:枚举
根据题目描述,我们知道,如果删除字符后的三个字符串相等,那么它们存在一个长度大于 的公共前缀。因此,我们可以枚举公共前缀的位置 ,如果当前下标 对应的三个字符不完全相等,那么公共前缀长度为 ,此时,我们判断 是否为 ,若是,返回 ,否则返回 ,其中 为三个字符串的长度和。
时间复杂度 ,其中 为三个字符串的最小长度。空间复杂度 。
class Solution:
def findMinimumOperations(self, s1: str, s2: str, s3: str) -> int:
s = len(s1) + len(s2) + len(s3)
n = min(len(s1), len(s2), len(s3))
for i in range(n):
if not s1[i] == s2[i] == s3[i]:
return -1 if i == 0 else s - 3 * i
return s - 3 * n
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for a solution that efficiently calculates the longest common prefix of the three strings.
- question_mark
Evaluate if the candidate handles edge cases, such as strings that cannot be made equal.
- question_mark
Consider how the candidate approaches calculating the necessary deletions and the final result.
常见陷阱
外企场景- error
Overcomplicating the solution with unnecessary operations or nested loops.
- error
Failing to account for edge cases, such as strings with no common prefix.
- error
Not optimizing for time complexity, especially when dealing with strings of varying lengths.
进阶变体
外企场景- arrow_right_alt
The problem can be extended to handle more than three strings.
- arrow_right_alt
A variant could involve restricting the number of deletions per string.
- arrow_right_alt
Another variant might require making the strings equal by removing characters from both ends instead of just the right side.