LeetCode解题报告 392. Is Subsequence [medium]
2016-10-26 17:09
423 查看
题目描述
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?
解题思路
由于子串不需要连续,只要保持位置不打乱原来的顺序就可以,因此用两个指针,一个指向原数列,一个指向目标子串即可,遍历一遍原数列可得到结果。时间复杂度分析
遍历一遍字符串t可得结果,因此时间复杂度为O(n)。代码如下:
class Solution { public: bool isSubsequence(string s, string t) { if (s.length()>t.length()) { return false; } else{ int l1=s.length(); int l2=t.length(); int k=0; for (int i=0; i<l2; i++) { if (s[k]==t[i]) { k++; } } if (k==l1) { return true; } else return false; } } };
相关文章推荐
- 【LeetCode】56.Merge Intervals(Medium)解题报告
- 【LeetCode】163.Missing Ranges(Medium)(带锁题)解题报告
- 【LeetCode】623.Add One Row to Tree(Medium)解题报告
- 【LeetCode】285.Inorder Successor in BST(Medium)(带锁题)解题报告
- LeetCode解题报告 199. Binary Tree Right Side View [medium]
- 【LeetCode】78.Subsets(Medium)解题报告
- 【LeetCode】337.House Robber III(Medium)解题报告
- 【LeetCode】325.Maximum Size Subarray Sum Equals k(Medium)解题报告
- 【LeetCode】277.Find the Celebrity(Medium)解题报告(带锁题)
- 【LeetCode】245.Shortest Word Distance III(Medium)(加锁题)解题报告
- 【LeetCode】90.Subsets II(Medium)解题报告
- 【LeetCode】376.Wiggle Subsequence(Medium)解题报告
- LeetCode解题报告 322. Coin Change [medium]
- 【LeetCode】320.Generalized Abbreviation(Medium)解题报告
- 【LeetCode】113.Path Sum II(Medium)解题报告
- 【LeetCode】156.Binary Tree Upside Down(Medium)(加锁题)解题报告
- 【LeetCode】109.Convert Sorted List to Binary Search Tree(Medium)解题报告
- 【LeetCode】274.H-Index(Medium)解题报告
- 【LeetCode】131.Palindrome Partitioning(medium)解题报告
- 【LeetCode】236.Lowest Common Ancestor of a Binary Tree(Medium)解题报告