leetcode解题报告:392. Is Subsequence

来源:互联网 发布:手机钢琴软件哪个好 编辑:程序博客网 时间:2024/06/06 09:09

题目:

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 tt 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;    }};


0 0