LeetCode | 0392. Is Subsequence判断子序列【Python】
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了LeetCode | 0392. Is Subsequence判断子序列【Python】,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1936字,纯文字阅读大概需要3分钟。
内容图文
![LeetCode | 0392. Is Subsequence判断子序列【Python】](/upload/InfoBanner/zyjiaocheng/643/9a3ef28acf7948f1bcfa0aaf21f714ae.jpg)
LeetCode 0392. Is Subsequence判断子序列【Easy】【Python】【双指针】
Problem
Given a string s and a string t, check if s is subsequence of t.
You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ace"
is a subsequence of "abcde"
while "aec"
is not).
Example 1:
s = "abc"
, t = "ahbgdc"
Return true
.
Example 2:
s = "axc"
, t = "ahbgdc"
Return false
.
Follow up:
If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B, and you want to check one by one to see if T has its subsequence. In this scenario, how would you change your code?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
问题
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。
你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。
字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
示例 1:
s = "abc"
, t = "ahbgdc"
返回 true
.
示例 2:
s = "axc"
, t = "ahbgdc"
返回 false
.
后续挑战 :
如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?
致谢:
特别感谢 @pbrother 添加此问题并且创建所有测试用例。
思路
双指针
i 指针作为 s 的索引,j 指针作为 t 的索引。每次 j 都要右移,如果 s[i] == t[j],i 要右移。
时间复杂度: O(min(len(s), len(t)))
空间复杂度: O(1)
Python代码
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
i, j = 0, 0
while i < len(s) and j < len(t):
if s[i] == t[j]:
i += 1
j += 1
return i == len(s)
代码地址
内容总结
以上是互联网集市为您收集整理的LeetCode | 0392. Is Subsequence判断子序列【Python】全部内容,希望文章能够帮你解决LeetCode | 0392. Is Subsequence判断子序列【Python】所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。