1. 程式人生 > 其它 >子序列(All in All, UVa 10340) 最大程度減少時間複雜度

子序列(All in All, UVa 10340) 最大程度減少時間複雜度

子序列(All in All, UVa 10340) 最大程度減少時間複雜度

原題:輸入兩個字串s和t,判斷是否可以從t中刪除0個或多個字元(其他字元順序不變),得到字串。例如,abcde可以得到bce,但無法得到dc。

解析:原有思路,逐個遍歷t字串0~len(t),看是否存在i再0~len(t)內使得滿足題目條件,但時間複雜度遠超解題要求。

不妨換種思路:

  定義一個計數器cnt,外層for迴圈遍歷t字串,內部if判斷s字串是否存在該字元,若存在則cnt自加,內部j自加,出現t字串或s字串遍歷到末尾的情況退出迴圈。判斷計數器cnt是否等於s字串的長度即可。

原始碼附下:

#include<iostream>
#include<string>

using namespace std;

int main(){
string s,t;
cin >> s >> t;
//cout<<s.size()<<'\t'<<t.size()<<endl;
int j=0, cnt=0;
for(int i=0; i<t.size(); i++){
if(t[i] == s[j] && j != s.size()){
cnt++;
j++;
}else if(j == s.size()) break;
else continue;
}
if(cnt == s.size()) cout<<"yes"<<endl;
else cout<<"no"<<endl;
return 0;
}