本題要考慮字串本身就存在tandem,
如測試用例
aaaaaaaaabbb
3
輸出結果應該是8而不是6,因為字串本身的tanderm時最長的
故要考慮字串本身的最大的tanderm和新增k個字元後最大的tanderm
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <set> using namespace std; int maxTandem(string& str){ for(int inteval = str.length()/2; inteval>=0; --inteval){ for(int i = 0 ; i <=str.length()-2*inteval; ++i){ bool flag = false; for(int j = i,k=i+inteval; j < i+inteval; j++,k++){ if(str[j] != str[k]){ flag = true; break; } } if(!flag) return inteval; } } return 0; } int main(){ string str; int k; cin >> str >> k; int len = str.length(); if(k>=len){ cout<<((k+len)%2 ? k+len-1:k+len)<<endl; }else{ int newlen = len+k, startIndex=newlen-newlen/2*2, p =newlen/2; for( p = newlen/2; p> k; -- p){ int startIndex=newlen-p*2; bool flag = false; for(int i = startIndex, j = startIndex+p; i < min(len,startIndex+p) && j < len; ++ i, ++ j){ if(str[i] != str[j]){ flag = true; break; } } if(!flag) break; } cout<<2*max(p,maxTandem(str))<<endl; } }
本題將上面兩個部分合並,即在字串s後面新增k個‘?’,再對整個字串搜尋
#include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; int main(){ string s; int k; cin >> s >> k; int slen = s.length(); s+=string(k,'?'); int len = s.length()/2, interval = len; for(interval = len; interval >=0; interval--){ bool flag = false; for(int p = 0; p<= s.length()-2*interval; ++ p){ flag = false; for(int i = p, j = p+interval; i < min(slen,p+interval) && j < slen; ++ i, ++ j){ if(s[j]!= '?' && s[i]!=s[j] ){ flag = true;break;} } if(!flag) break; } if(!flag) break; } cout<<2*interval<<endl; }