[DP]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.

题目分析:

1、题目要求根据传入的两个字符串s和t,判断s是否为t的子序列;

2、该题算法的构思比较简单。按从头到尾的顺序,先取出s的第一个字符,从t的头部开始依次向尾检验直至找到匹配项,此后再从s中取出第二个字符从t中找到匹配项的后一项开始继续往后检验,直至s取完或者t取完。

3、代码设计方面,设置两个参数int sL和int tL表示当前取出元素的下标,当找到匹配项后,sL和tL都++。设置新函数f引入tL和sL两个新参数,利用递归的方法来实现代码的简化。由于每个字符只检验一次,那么函数的时间复杂度为O(len(s)+len(n))。

4、递归的终止条件分为两个:sL == s.size(),即表示sL已经到s的末尾,s已检验完毕,返回true;tL = t.size(),即tL已到t末尾,t已检验完,返回false。

代码:

bool f(string &s, int sL, string &t, int tL){
    if(sL == s.size())
        return true;
        
    while(s[sL] != t[tL] && tL < t.size())
        tL++;
        
    if(tL == t.size())
        return false;
        
    sL++;
    tL++;
    
    return f(s, sL, t, tL);
}


class Solution {
public:
    bool isSubsequence(string s, string t){
        return f(s, 0, t, 0);
    }
};

代码完成中有几个细节需要处理:
1、特殊情况,比如s为空的情况。因此考虑将sL == s.size()放到函数开头,因为当sL = s.size() = 0时依然为true,且s[sL]会发生数组越界,必须放在其前。
2、将tL == t.size()放在循环的后面,因为若寻找不到匹配项循环跳出后实际上 tL = t.size(),应此时检验并返回false。
3、f引入两个字符串参数时应进行取址调用,否则将造成大量的空间申明。发生memory limit exceeded的错误。

你可能感兴趣的:([DP]392. Is Subsequence)