最长前缀后缀

时间:2016-09-15 16:10:13

标签: c++ stack

给定一个字符串,找到最长的正确前缀的长度,这也是一个正确的后缀。 例: 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;
}

测试用例失败了 “khwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhvkhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkgkhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhvkhwkhpkhnkhwkhpkhtkhwrkhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhpkhnkhwkhpkhtkhwkhpkhnkhdkhwkhpkhnkhwkhpkhtkhokhwkhpkhnkhwkhpkhtkhwkhpkhnkhwkhfkhwkhrkhwkhpkhnckhwkhp”

正确的输出是155而我得到55。

2 个答案:

答案 0 :(得分:1)

问题在于,在测试前缀(堆栈)是否与后缀匹配时,从堆栈中删除整个匹配部分。有时包括真正最长前缀的尾部。

我在重置std::cout << charStack.size() << '\n';后立即添加了count,这是输出的相关部分:

212
211
154
153

如您所见,您从未尝试匹配前缀长度155

答案 1 :(得分:0)

这是我的KMP代码: -

#include <bits/stdc++.h>
using namespace std;


int main(void){
    int t;
    scanf("%d",&t);
    while(t--){
        string s;
        cin>>s;
        int n = s.length();
        int arr[n];
        arr[0] = 0;
        int len = 0;
        for(int i = 1;i<n;){
            if(s[len]==s[i]){
                len++;
                arr[i++] = len;
            }
            else{
                if(len!=0){
                    len = arr[len-1];
                }
                else{
                    arr[i] = 0;
                    i++;
                }
            }
        }
        cout<<arr[n-1]<<endl;
    }


    return 0;
}

时间复杂度为O(N)