目录
LeetCode392 判断子序列
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool isSubsequence(string s, string t) {
int m=s.size(),n=t.size();
if(m>n) return false;
int i=0,j=0;
while(i<m&&j<n){
if(s[i]==t[j]) i++;
j++;
}
return i==m;
}
};
时间复杂度:O(m)
空间复杂度:O(1)
LeetCode522 最长特殊序列 II
如果某个字符串的子序列是特殊序列,则该字符串一定是特殊序列,因此只需要判断每个完整的字符串是否为特殊序列。
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
bool check(string s1,string s2){//检查s1是否为s2的子序列
int i=0,j=0;
int m=s1.size(),n=s2.size();
if(m>n) return false;
while(i<m&&j<n){
if(s1[i]==s2[j]) i++;
j++;
}
return i==m;
}
int findLUSlength(vector<string>& strs) {
int n=strs.size();
int res=-1;
for(int i=0;i<n;i++){
bool f=true;
for(int j=0;j<n;j++){
if(i!=j&&check(strs[i],strs[j])){
f=false;
break;
}
}
if(f) res=max(res,(int)strs[i].size());
}
return res;
}
};
时间复杂度:,l为字符串平均长度
空间复杂度:O(1)