給定一個字符串,找到最長正確前綴的長度,這也是一個適當的後綴。 示例: S = abab則長度爲2,前綴='ab',後綴'ab'是公共的。最長前綴後綴
這是我的代碼使用堆棧。它適用於某些情況,而不適用於某些情況。我很難理解爲什麼它不適用於某些情況。任何人都可以解釋我做錯了什麼?
int main(){
long int T,i,j;
/* total test case */
cin>>T>>ws;
while(T--){
string str;
long int count = 0;
getline(cin,str);
stack<char> charStack;
/** push all character till second last **/
for(i=0;i!=str.length()-1;i++){
charStack.push(str[i]);
}
j = str.length()-1;
while(!charStack.empty()){
char ch = charStack.top();
charStack.pop();
if(ch==str[j]){
count++;
j--;
}else {
count = 0;
j = str.length()-1;
}
} //inner while
cout<<count<<"\n";
} //outer while
return 0;
}
它是失敗的測試用例 「khwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhvkhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkgkhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhvkhwkhpkhnkhwkhpkhtkhwrkhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrk hwkhpkhnckhwkhp「
正確的輸出是155,而我越來越55。
您從比較從堆棧(字符串的結束)的頂部字符的字符字符串的結尾(即它們自己),這很奇怪。什麼情況下完全失敗? – Ap31
堆棧中的最後一項包含字符串的第二個最後一個字符,而不是最後一個字符。 – randy