15,742,973 members
4.00/5 (1 vote)
See more:
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.
C#
#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;

}
Posted
Updated 3-May-10 3:13am
v4

## Solution 2

Try the following code:

C++
#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;
}

:)

## Solution 1

Inside the inner for loop you should change if (s[i]==s[j]) to if (s[i]==s[j-1])...