帮助找到最长的对称子字符串 [英] Help on finding the longest symmetric sub-string

查看:104
本文介绍了帮助找到最长的对称子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请在此程序上需要帮助.
我没有得到正确的结果...(程序应该找到最长的对称子字符串并显示它)
感谢您的帮助.

Please I need help with this program.
I am not getting proper result...(The program should find the longest symmetric sub-string and display it)
Thanks for the help.

#include <iostream>
#include<string>
using namespace std;
char s[30];
int i=0, j, first, last, length,subleng, maxi=0;
void main ()
{
    cout<<"Enter a string to process \n";
    cin>>s[i];
    while (s[i]!='\0')
    {

            cin>>s[i];
            i++;
    }
    length = static_cast<int>(strlen(s));
    for(i=0 ; i<length ; i++)
    {
        for(j=length; j>=0; j--)
        {
            if (s[i]==s[j])
            {
                subleng= j-i;
                if(subleng>maxi)
                {
                    first=i;
                    last=j;
                    maxi= subleng;
                }

            }
        }
    }
    cout<<"The longest symmetric substring is : \n";
    for (i=first ; i<last ; i++)
    {

    cout<<s[i];
    }
    cout<<endl<<endl;

}

推荐答案

尝试以下代码:

Try the following code:

#include <iostream>
#include<string>
using namespace std;
char s[30];
int i=0, j, first, last, length,subleng, maxi=0;
void main ()
{
    cout<<"Enter a string to process \n";
    cin >> s;
    length = static_cast<int>(strlen(s));
    for(i=0 ; i<length ; i++)
    {
        int j,k,n;
        for (n=0; n<2; n++)
        {// 0 => even symmetric substrings, 1 => odd symmetric substrings
          j = i-n;
          k = i+1;
          subleng = n;
          while ( j>=0 && k<length && s[j]==s[k])
          {
            subleng +=2;
            j--; k++;
          }
          if( subleng > maxi)
          {
            first= j + 1;
            maxi= subleng;
          }
        }
    }
    cout<<"The longest symmetric substring is : \n";
    for (i=0 ; i<maxi ; i++)
    {
      cout<<s[first+i];
    }
    cout<<endl<<endl;
}


:)


在内部for循环中,您应该将if (s[i]==s[j])更改为if (s[i]==s[j-1]) ...
Inside the inner for loop you should change if (s[i]==s[j]) to if (s[i]==s[j-1])...


这篇关于帮助找到最长的对称子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆