Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all articles
Browse latest Browse all 40121

Palindrome String C++ Suggestion for optimization

$
0
0

It's my code to find palindrome in string ,But it ain't a good piece.How can I optimize this code or is there any efficient algorithm for this type of problems...And I think for some cases it is also not giving me correct output.Thanks for the help

//Have to work on it!!!!!!!!!!!!!!!!!!!!!//
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char input[100];
    char modified[100]="";  //This ll be modified form only with alphabets
   cout<<"Enter text:\n";
    gets(input);

    int t=strlen(input);
int s=0;
    for(int e=0;e<t;e++)
    {
        if(islower(input[e]))
        {
            modified[s] =input[e];
            s++;
        }
    }
printf("\nThe modified version of the text is:");
    puts(modified);

int l=strlen(modified);
    for(int a=0;a<(l-1);a++)
        for(int b=a+1;b<l;b++)
    {
        if(modified[a]==modified[b])
        {
            if((b-a)%2==0) //even
            {
                int x=(a+b)/2;
                int countt=0;
                for(int p=a,q=b;p<x && q>x;p++,q--)
                {
                    if(modified[p]==modified[q])
                        countt++;

                    else if(modified[p]!=modified[q])
                        break;

                    if(countt==(b-a)/2)
                    {
                        cout<<"Palindrome:";
                        for(int i=a;i<=b;i++)
                        {
                            putchar(modified[i]);
                        }
                        cout<<endl;
                    }
                }
            }

            else if((b-a)%2!=0) //odd
            {
                int y=(a+b+1)/2;
                int z=(a+b-1)/2;
                int count2=0;
                for(int w=a,r=b;w<y && r>z ;w++,r--)
                {
                                        if(modified[w]==modified[r])
                        count2++;

                    else if(modified[w]!=modified[r])
                        break;

                    if(count2==(b-a+1)/2)
                    {
                        cout<<"Palindrome:";
                        for(int o=a;o<=b;o++)
                        {
                            putchar(modified[o]);
                        }
                        cout<<endl;
                    }
                }
            }
        }
    }
}

Viewing all articles
Browse latest Browse all 40121

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>