首页 > 学院 > 开发设计 > 正文

392. Is Subsequence -Medium

2019-11-14 12:44:03
字体:
来源:转载
供稿:网友

Question

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).

给出两个字符串s, t,判断s是否是t的子集。t大约有500000个字符, s不超过100个字符。这里的子集的判断是允许删除一些中间的字符得到的剩余字符相同(也就是不需要连续相同的字符串)

Example

s = “abc”, t = “ahbgdc”

Return true.


s = “axc”, t = “ahbgdc”

Return false.

Solution

这道题还是比较简单的,如果s是t的子集,那么s中的所有字符必然按照相同的顺序出现在t中,所以我们可以分别建立两个字符串的索引,每当t中出现s的当前字符,就搜索s的下一个字符,直到s的所有字符均在t中找到

class Solution(object): def isSubsequence(self, s, t): """ :type s: str :type t: str :rtype: bool """ # 如果s是空字符串,那么它是任意字符串的子集 if len(s) == 0: return True index_s, index_t = 0, 0 # 遍历t for current_t in t: # 如果s的当前元素被找到,则继续寻找下一个s if s[index_s] == current_t: index_s += 1 # 如果s的所有字符都被找到,代表s是t的子集 if index_s == len(s): return True # 如果搜索完t仍然没有找全s,代表s不是t的子集 return False
上一篇:vs2012转成vs2010

下一篇:java中的异常分类

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表