LeetCode 题解工作台

最长特殊序列 Ⅰ

给你两个字符串 a 和 b ,请返回 这两个字符串中 最长的特殊序列 的长度。如果不存在,则返回 -1 。 「最长特殊序列」 定义如下:该序列为 某字符串独有的最长 子序列 (即不能是其他字符串的子序列) 。 字符串 s 的子序列是在从 s 中删除任意数量的字符后可以获得的字符串。 例如, "abc…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

如果字符串 `a` 和 `b` 相等,那么它们没有特殊序列,返回 `-1`;否则,返回长度较长的字符串的长度。 时间复杂度 ,其中 为字符串 `a` 和 `b` 中较长的字符串的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个字符串 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 <= 100
  • a 和 b 由小写英文字母组成
lightbulb

解题思路

方法一:脑筋急转弯

如果字符串 ab 相等,那么它们没有特殊序列,返回 -1;否则,返回长度较长的字符串的长度。

时间复杂度 O(n)O(n),其中 nn 为字符串 ab 中较长的字符串的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        return -1 if a == b else max(len(a), len(b))
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

最长特殊序列 Ⅰ题解:String-driven solution … | LeetCode #521 简单