NOJ [1251] Find the Palindrome

来源:互联网 发布:python 转置 优先级 编辑:程序博客网 时间:2024/05/30 05:15
  • [1251] Find the Palindrome

    • The problem is pretty easy, giving you a very long string, you have to find the first longest palindrome in the string. (Case-insensitive)
    • 输入
    • First line contain a integer T (T <= 100), means the test case.
      And the following T lines, for each line, there is a string is make up with the uppercase and lowercase.
      The string's length is less than 10000.
    • 输出
    • For each test case, you should print the longest palindrome, if there are muti-case, print first of them.
    先用了中心法来求回文串,效率不高,超时了很多次,后来使用了白书上的方法,中间枚举i,效率高了很多


    所以说,时间上差很多

    1.中心法代码

    #include<stdio.h>#include<string.h>char str[10010];int max_len,left,right,len;void search_longest_str(int l,int r){char a,b;a=str[l];    b=str[r];    if(a>='A' && a<='Z')        a=a-'A'+'a';   if(b>='A' && b<='Z')        b=b-'A'+'a';while(l>=0 && r<=len-1 && a==b){    l--;r++;        a=str[l];        b=str[r];        if(a>='A' && a<='Z')        a=a-'A'+'a';    if(b>='A' && b<='Z')        b=b-'A'+'a';  }if(r-l+1>max_len){ max_len=r-l+1; left=l+1; right=r-1;} }int main(){int t;while(~scanf("%d",&t)){while(t--){scanf("%s",str);len=strlen(str);max_len=-1;for(int i=0;i<len;i++){search_longest_str(i,i);if(i+1<len)   search_longest_str(i,i+1);}for(int i=left;i<=right;i++)    printf("%c",str[i]);        printf("\n");}}return 0;}

    2.中间枚举i的代码

    #include<stdio.h>#include<string.h>char str[10010];char newstr[10010];int pos[10010];int main(){int t;scanf("%d",&t);while(t--){char a,b;int left,right,i,j,k,len;scanf("%s",str);len=strlen(str);int max_len=0;for(i=0;i<len;i++){if(str[i]>='A'&&str[i]<='Z')   newstr[i]=str[i]-'A'+'a';            else               newstr[i]=str[i];                pos[i]=i;}for(i=0;i<len;i++){for(j=0;i-j>=0 && i+j<len;j++){if(newstr[i-j]!=newstr[i+j])   break;                    if(2*j+1>max_len)                    {                    max_len=2*j+1;                    left=pos[i-j];                    right=pos[i+j];                    }}for(j=0;i-j>=0 && i+j+1<len;j++){            if(newstr[i-j]!=newstr[i+j+1])               break;                    if(2*j+2>max_len)                    {                    max_len=2*j+2;                    left=pos[i-j];                    right=pos[i+j+1];                    }}}for(i=left;i<=right;i++)  printf("%c",str[i]);        printf("\n");}return 0;}






0 0