Problem
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
s = "abc", t = "ahbgdc"Follow up:
Return true.
s = "axc", t = "ahbgdc"
Return false.
Algorithm
整理一下题意:给定字符串s和t,检查s是否是t的子串。已知s和t都只含小写字母。关于子串,注意s的字母可以在t中不连续。
首先想到的解法是对s中的字母逐个判断。具体来说,先拿s的第0位与t中的字母进行匹配,若没有找到,则返回false。若找到,则标记t中匹配成功的位,然后s的第1位开始从t中匹配成功的位开始新一轮的匹配。如此类推,若t中所有字母遍历一遍后,s中的每个字母也全部匹配成功,则返回true。代码如下。
//递归版本,时间复杂度O(2^n)
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.size()==0) return true;
if(s.size()==1){
for(int i=0;i<t.size();i++){
if(s[0]==t[i]) return true;
}
return false;
}
int index=-1;
bool isfind=false;
for(int i=0;i<t.size();i++){
if(s[0]==t[i]) {
index=i;
isfind=true;
break;
}
}
if(isfind) s=s.substr(1);
else return false;
if(index==t.size()-1) return false;
else t=t.substr(index+1);
return isSubsequence(s,t);
}
};
完成题目后提交,未通过,显示Memory Limit Exceeded,内存空间不足。看来要减少空间使用。分析代码,觉得很有可能问题出在substr()函数。经查阅资料,发现string类的substr()函数的时间复杂度是O(n^2),且内部会重新声明新的字符串。也就是每次使用substr()都会增加内存空间的占用。而isSequence()本身是递归函数,不怪乎无法通过了。
于是考虑新的方法。整体思路不变,考虑是否需要每次都把新串存下来。实际上这是不必要的,只需要知道每次s在t中的匹配到t的哪一位就可以了。于是只需要对匹配成功时t的下标进行记录。判断s是否匹配成功的条件变为在t的所有位遍历后,s是否已完成遍历。代码如下。
//递归版本,时间复杂度O(n)
class Solution {
public:
bool isSubsequence(string s, string t) {
if(s.size()==0) return true;
if(t.size()==0) {
if(s.size()==0) return true;
else return false;
}
int i,j;
for(i=0,j=0;i<t.size();i++){
if(s[j]==t[i]) j++;
}
if(j==s.size()) return true;
else return false;
}
};