392. Is Subsequence
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.
题意:
S是否是T的子串?子串指的是T删除一些元素后,剩下的元素还要保持之前在T中的相关顺序。
解答:
遍历的方法。用一个变量pos记录已经扫描到T中的位置,思路是对于S中的每一个元素,在T中从pos后的位置开始查找,这样的话就避免对T中元素重复遍历了。第一次提交的时候,我因为忘记考虑S的长度不能超过T的长度所以WA了一次。
代码:[cpp] view plain
复杂度:
复杂度就是遍历了一遍S或者T中元素,所以是O(n)。
本文介绍了一个经典的字符串问题——如何判断一个字符串是否为另一个字符串的子序列。通过一个高效的遍历算法实现,避免了对较长字符串的重复遍历,提高了算法效率。

511

被折叠的 条评论
为什么被折叠?



