LeetCode 题解工作台
最长特殊序列 Ⅰ
给你两个字符串 a 和 b ,请返回 这两个字符串中 最长的特殊序列 的长度。如果不存在,则返回 -1 。 「最长特殊序列」 定义如下:该序列为 某字符串独有的最长 子序列 (即不能是其他字符串的子序列) 。 字符串 s 的子序列是在从 s 中删除任意数量的字符后可以获得的字符串。 例如, "abc…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
如果字符串 `a` 和 `b` 相等,那么它们没有特殊序列,返回 `-1`;否则,返回长度较长的字符串的长度。 时间复杂度 ,其中 为字符串 `a` 和 `b` 中较长的字符串的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你两个字符串 a 和 b,请返回 这两个字符串中 最长的特殊序列 的长度。如果不存在,则返回 -1 。
「最长特殊序列」 定义如下:该序列为 某字符串独有的最长子序列(即不能是其他字符串的子序列) 。
字符串 s 的子序列是在从 s 中删除任意数量的字符后可以获得的字符串。
- 例如,
"abc"是"aebdc"的子序列,因为删除"aebdc"中斜体加粗的字符可以得到"abc"。"aebdc"的子序列还包括"aebdc"、"aeb"和""(空字符串)。
示例 1:
输入: a = "aba", b = "cdc" 输出: 3 解释: 最长特殊序列可为 "aba" (或 "cdc"),两者均为自身的子序列且不是对方的子序列。
示例 2:
输入:a = "aaa", b = "bbb" 输出:3 解释: 最长特殊序列是 "aaa" 和 "bbb" 。
示例 3:
输入:a = "aaa", b = "aaa" 输出:-1 解释: 字符串 a 的每个子序列也是字符串 b 的每个子序列。同样,字符串 b 的每个子序列也是字符串 a 的子序列。
提示:
1 <= a.length, b.length <= 100a和b由小写英文字母组成
解题思路
方法一:脑筋急转弯
如果字符串 a 和 b 相等,那么它们没有特殊序列,返回 -1;否则,返回长度较长的字符串的长度。
时间复杂度 ,其中 为字符串 a 和 b 中较长的字符串的长度。空间复杂度 。
class Solution:
def findLUSlength(self, a: str, b: str) -> int:
return -1 if a == b else max(len(a), len(b))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because a single string comparison suffices, and space complexity is O(1) since no additional data structures are required. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Expect a string-driven comparison rather than generating all subsequences.
- question_mark
Watch for equal strings where the answer is -1.
- question_mark
Longer strings directly indicate the longest uncommon subsequence when strings differ.
常见陷阱
外企场景- error
Attempting to enumerate all subsequences, which is unnecessary for this problem.
- error
Confusing the longest common subsequence with the longest uncommon subsequence.
- error
Forgetting to handle identical strings, which must return -1.
进阶变体
外企场景- arrow_right_alt
Longest Uncommon Subsequence II with multiple strings in the input array.
- arrow_right_alt
Find the longest uncommon subsequence with character restrictions or special symbols.
- arrow_right_alt
Determine the longest uncommon substring instead of subsequence.