您的位置:首页 > 产品设计 > UI/UE

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, 
"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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: