题目:
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);
}
};
本文介绍了一个简单的算法,用于判断一个字符串是否为另一个字符串的子序列。通过递归方法实现了高效检查,时间复杂度为O(len(s)+len(t))。
1358

被折叠的 条评论
为什么被折叠?



