题目:判断子序列
原题链接:判断子序列
刚一开始,觉得用暴力也才O(n^2),想先试一下能不能过,谁知道果然过不了。代码如下:
class Solution {
public:
bool isSubsequence(string s, string t) {
int ls = s.size(), lt = t.size();
if(ls == 0 && lt == 0) return true;
for(int i = 0; i < lt - ls; i++){
int j = 0, k = i;
while(k < lt && j < ls){
if(t[k] != s[j]) k++;
else{
k++;
j++;
}
}
if(j == ls) return true;
}
return false;
}
};
结果如下:
然后仔细一想,不对啊,好像可以优化;外面的那一层for循环是没有必要的的,修改后如下:
class Solution {
public:
bool isSubsequence(string s, string t) {
int ls = s.size(), lt = t.size();
if(ls == 0 && lt == 0) return true;
int j = 0, k = 0;
while(k < lt && j < ls){
if(t[k] != s[j]) k++;
else{
k++;
j++;
}
}
if(j == ls) return true;
return false;
}
};
这样就通过了测试:
不过速度貌似还是挺慢的,暂时没想到别的,先就这样吧~~
题外话:
坏脾气的消失,可以准确地反映智慧的增长。
——尼采