- Leetcode 3302. Find the Lexicographically Smallest Valid Sequence
- 1. 解题思路
- 2. 代码实现
- 题目链接:3302. Find the Lexicographically Smallest Valid Sequence
1. 解题思路
这一题的话由于至多只能够修改一个字符,因此,我们就是要考察每一个字符前正向的最大公共子序列的长度和其后方的从后往前的最大公共子序列的长度。如果两者相加不小于目标目标字符串word2
的长度减一,即表示调整当前位置上的字符的话即可获得一个子串使之与目标字符串word2
相同。
然后,我们定位到第一个满足上述条件的位置,通过调整该位置获得的字符串就是最优的选项。
最后,我们找到调整该位置所能够获得字符串的index即可。
2. 代码实现
给出python代码实现如下:
class Solution:def validSequence(self, word1: str, word2: str) -> List[int]:n, m = len(word1), len(word2)if m == 1:return [0]# prefixprefix = [0 for _ in word1]i, j = 0, 0while j < m:while i < n and word1[i] != word2[j]:prefix[i] = ji += 1if i >= n:breakj += 1prefix[i] = ji += 1while i < n:prefix[i] = ji += 1# suffixi, j = n-1, m-1suffix = [0 for _ in word1]while j >= 0:while i >= 0 and word1[i] != word2[j]:suffix[i] = m-1-ji -= 1if i < 0:breakj -= 1suffix[i] = m-1-ji -= 1while i >= 0:suffix[i] = m-1-ji -= 1# find target idxidx = -1if word1[0] != word2[0] and suffix[1] >= m-1:idx = 0else:for i in range(1, n-1):if prefix[i-1] + suffix[i+1] >= m-1 and prefix[i] != prefix[i-1]+1:idx = ibreakif idx == -1 and prefix[n-2] >= m-1:idx = n-1# get all the indexif idx == -1:return []i, j = 0, 0ans = []while j < m:while i < idx and word1[i] != word2[j]:i += 1if i >= idx:breakans.append(i)j += 1i += 1if j < m:ans.append(i)i += 1j += 1while j < m:while i < n and word1[i] != word2[j]:i += 1if i >= n:breakans.append(i)j += 1i += 1return ans
提交代码评测得到:耗时1200ms,占用内存55.7MB。