最长回文子串

原串中连续出现且正着看与倒着看一样的串,这里忽略非字母

#include <iostream>
#include <fstream>
#include <cctype>

int main(void)
{
    using namespace std;

    const int MAXLEN=100;
    char src[MAXLEN];   //
    char disposed[MAXLEN];   //处理过的
    int index[MAXLEN];   //记录处理过的对应的下标

    ifstream fin=ifstream("Text.txt");
    fin.getline(src,MAXLEN);   //getline()去掉了换行符,如果有的话,末尾加 ''

    int count=0;   //记录加入到处理后的字母总个数
    int cursor=0;   //指向src的每一个

    /*下面开始预处理*/
    while (src[cursor]!='')   //结尾
    {
        if (isalpha(src[cursor]))   //不是字母就不管了
        {
            disposed[count]=toupper(src[cursor]);
            index[count]=cursor;   //记录对应的源的下标
            count++;
        }

        cursor++;
    }

    /*下面干正事*/
    int x,y;   //记录最长的首尾下标,在dispose中的
    int myMaxLen=0;   //最长的长度

    for (int i=0;i<count;i++)
    {
        for (int j=i;j<count;j++)    //i,j之间的为要处理的,其实列出了所有可能情况
        {
            int m=i,n=j,thisLen=0,flag=0;
            while (m<=n)
            {
                if (disposed[m]==disposed[n])
                {
                    if(m!=n)  thisLen+=2;
                    else  thisLen+=1;
                    m++,n--;
                }
                else
                {
                    flag=1;
                    break;   //直接跳出while
                }
            }

            if ((!flag)&&(thisLen>myMaxLen))   //不是break跳出的
            {
                x=i,y=j;
                myMaxLen=thisLen;
            }
        }
    }
    
    cout<<"源字符串:
"<<src<<endl;

    cout<<"
处理后字符串:
";
    for (int i=0;i<count;i++)
    {
        cout<<disposed[i];
    }

    cout<<"

最长在处理过字符串中情况:
";
    for (int i=x;i<=y;i++)
    {
        cout<<disposed[i];
    }

    cout<<"

最长在源字符串中情况:
";
    for (int i=index[x];i<=index[y];i++)
    {
        cout<<src[i];
    }
    cin.get();
    return 0;
}

总结:

1. 预处理,把原来的串中的非字母剔除并且全改成大写,结果放到一个处理过的数组,并且记录下标对应关系

2. 其实也是列举了一个字符串的所有子串,看它是不是合适且是不是最长的,两层for循环里面的就是那次要处理

原文地址:https://www.cnblogs.com/jiayith/p/3484852.html