欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Leetcode 3302. Find the Lexicographically Smallest Valid Sequence

Leetcode 3302. Find the Lexicographically Smallest Valid Sequence

2024/10/26 1:22:00 来源:https://blog.csdn.net/codename_cys/article/details/142637431  浏览:    关键词:Leetcode 3302. Find the Lexicographically Smallest Valid Sequence
  • 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。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com