Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++ STL Beginner
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;
 
}
Posted 3-May-10 2:40am
7mesho428
Edited 3-May-10 4:13am
CPallini328.4K
v4
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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;
}
Smile | :)
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Maciej Los 205
1 Richard MacCutchan 185
2 DamithSL 170
3 Tomas Takac 146
4 OriginalGriff 132
0 OriginalGriff 5,130
1 DamithSL 4,237
2 Maciej Los 3,700
3 Kornfeld Eliyahu Peter 3,470
4 Sergey Alexandrovich Kryukov 2,846


Advertise | Privacy | Mobile
Web04 | 2.8.141216.1 | Last Updated 3 May 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100