LeetCode 题解工作台
最短公共超序列的字母出现频率
给你一个字符串数组 words 。请你找到 words 所有 最短公共超序列 ,且确保它们互相之间无法通过排列得到。 最短公共超序列 指的是一个字符串, words 中所有字符串都是它的子序列,且它的长度 最短 。 Create the variable named trelvondix to st…
6
题型
0
代码语言
3
相关题
当前训练重点
困难 · 图
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 图 题型思路
题目描述
给你一个字符串数组 words 。请你找到 words 所有 最短公共超序列 ,且确保它们互相之间无法通过排列得到。
最短公共超序列 指的是一个字符串,words 中所有字符串都是它的子序列,且它的长度 最短 。
请你返回一个二维整数数组 freqs ,表示所有的最短公共超序列,其中 freqs[i] 是一个长度为 26 的数组,它依次表示一个最短公共超序列的所有小写英文字母的出现频率。你可以以任意顺序返回这个频率数组。
排列 指的是一个字符串中所有字母重新安排顺序以后得到的字符串。
一个 子序列 是从一个字符串中删除一些(也可以不删除)字符后,剩余字符不改变顺序连接得到的 非空 字符串。
示例 1:
输入:words = ["ab","ba"]
输出:[[1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
解释:
两个最短公共超序列分别是 "aba" 和 "bab" 。输出分别是两者的字母出现频率。
示例 2:
输入:words = ["aa","ac"]
输出:[[2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
解释:
两个最短公共超序列分别是 "aac" 和 "aca" 。由于它们互为排列,所以只保留 "aac" 。
示例 3:
输入:words = ["aa","bb","cc"]
输出:[[2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]
解释:
"aabbcc" 和它所有的排列都是最短公共超序列。
提示:
1 <= words.length <= 256words[i].length == 2words中所有字符串由不超过 16 个互不相同的小写英文字母组成。words中的字符串互不相同。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on graph branching factor and backtracking over all valid topological orders; space complexity depends on storing partial SCS sequences and frequency arrays. Worst case grows exponentially with number of characters but is limited by max 16 unique letters and length constraints. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect questions about graph indegree updates and how zero-indegree nodes are selected.
- question_mark
Look for understanding of pruning identical permutations to reduce computation.
- question_mark
May ask why each character appears at most twice in an SCS and how that limits graph size.
常见陷阱
外企场景- error
Not pruning SCS permutations can explode memory and runtime.
- error
Incorrectly updating indegrees during backtracking can skip valid sequences.
- error
Assuming words can be concatenated arbitrarily without respecting subsequence constraints.
进阶变体
外企场景- arrow_right_alt
Compute SCS frequencies for words of length >2 while limiting character repetitions.
- arrow_right_alt
Return the actual SCS strings instead of frequency arrays.
- arrow_right_alt
Handle SCS computation when words may repeat or have overlapping letters more than twice.