leetcode解题报告:392. Is Subsequence
2016-11-23 15:48
344 查看
题目:
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,
a subsequence of
not).
Example 1:
s =
Return
Example 2:
s =
Return
难度:Medium`
解题思路: 要判断S是否是T的子串(注意不一定要是连续的),我们可以通过动态规划的思想逐步减小问题的规模。 比如说对于s[1~i]而言,我们已经判断出了它是t[1~j]中的子串,那么我们下一步就只需要判断s[i+1~最后一位]是否是t[j+1~最后一位]的子串,如果是,那么s就是t的子串,如果不是那么s就不是t的子串。 假设s的规模是n,t的规模为m,那么总的时间复杂度就是O(max(n,m))
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.
难度:Medium`
解题思路: 要判断S是否是T的子串(注意不一定要是连续的),我们可以通过动态规划的思想逐步减小问题的规模。 比如说对于s[1~i]而言,我们已经判断出了它是t[1~j]中的子串,那么我们下一步就只需要判断s[i+1~最后一位]是否是t[j+1~最后一位]的子串,如果是,那么s就是t的子串,如果不是那么s就不是t的子串。 假设s的规模是n,t的规模为m,那么总的时间复杂度就是O(max(n,m))
class Solution { public: bool isSubsequence(string s, string t) { int ssize=s.size(); int tsize=t.size(); int i = 0; int j = 0; while(i<ssize&&j<tsize) { if(s[i]==t[j]) { i++; j++; } else { j++; } } return i==ssize; } };
相关文章推荐
- [Leetcode] 446. Arithmetic Slices II - Subsequence 解题报告
- 【LeetCode】521. Longest Uncommon Subsequence I 解题报告(Python)
- [Leetcode] 521. Longest Uncommon Subsequence I 解题报告
- [Leetcode] 522. Longest Uncommon Subsequence II 解题报告
- 【LeetCode】674. Longest Continuous Increasing Subsequence 解题报告
- 【LeetCode】376.Wiggle Subsequence(Medium)解题报告
- [Leetcode] 674. Longest Continuous Increasing Subsequence 解题报告
- [LeetCode]Min Stack,解题报告
- LeetCode-Median of Two Sorted Arrays-解题报告
- [Leetcode] 359. Logger Rate Limiter 解题报告
- 【LeetCode】442.Find All Duplicates in an Array解题报告
- [LeetCode] 4Sum 解题报告
- 【LeetCode】412.Fizz Buzz(easy)解题报告
- [leetcode]133. Clone Graph@Java解题报告
- Leetcode 90. Subsets II 子集2 解题报告
- Leetcode 461. Hamming Distance 汉明距离 解题报告
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- [leetcode] 202. Happy Number 解题报告
- [Leetcode] 715. Range Module 解题报告
- Swap Nodes in Pairs LeetCode 解题报告