小米算法第1道字符串,我也来提供一个思路
根据两个字符串的长度建立一个dp数组,相等的字符置1,然后遍历,时间复杂度有点高
#include<iostream>
#include<string>
#include<vector>
using namespace std;
void cal(string text, string pa, int & start, int & end){
int len1=text.length();
int len2=pa.length();
vector<vector<int>> dp(len2,vector<int>(len1));
for(int i=0;i<len2;i++){
for(int j=0;j<len1;j++){
if(text[j]!=pa[i]) dp[i][j]=0;
else dp[i][j]=1;
}
}
start=-1; end=-1;
int sum=0,sumt=10000;
for(int j=0;j<len1;j++){
int i=0;
int t=0;
if(dp[i][j]==1&&(j+1)<len1&&dp[i][j+1]!=1){
sum++; t=j; i++; t++;
while(i<len2){
while(t<len1&&dp[i][t]!=1) {
t++; sum++;
}
i++;
}
if(sum<sumt){
sumt=sum;
sum=0;
start=j;
end=t;
}
}
}
}
int main (){
vector<string> data;
string mm;
while(cin>>mm){
data.push_back(mm);
int len=data.size();
for(int i=0;i<len;i=i+2){
int x=0,y=0;
cal(data[i],data[i+1],x,y);
cout<<x<<" "<<y<<endl;
}
}
#include<string>
#include<vector>
using namespace std;
void cal(string text, string pa, int & start, int & end){
int len1=text.length();
int len2=pa.length();
vector<vector<int>> dp(len2,vector<int>(len1));
for(int i=0;i<len2;i++){
for(int j=0;j<len1;j++){
if(text[j]!=pa[i]) dp[i][j]=0;
else dp[i][j]=1;
}
}
start=-1; end=-1;
int sum=0,sumt=10000;
for(int j=0;j<len1;j++){
int i=0;
int t=0;
if(dp[i][j]==1&&(j+1)<len1&&dp[i][j+1]!=1){
sum++; t=j; i++; t++;
while(i<len2){
while(t<len1&&dp[i][t]!=1) {
t++; sum++;
}
i++;
}
if(sum<sumt){
sumt=sum;
sum=0;
start=j;
end=t;
}
}
}
}
int main (){
vector<string> data;
string mm;
while(cin>>mm){
data.push_back(mm);
int len=data.size();
for(int i=0;i<len;i=i+2){
int x=0,y=0;
cal(data[i],data[i+1],x,y);
cout<<x<<" "<<y<<endl;
}
}