I use the following code to get the input
int main() {
int x=0,value=0;
cin>>x;
string str;
for(int i=0;i<x;++i){
cin>>str;
value = findpalindrome(str);
cout<<value<<endl;}
return 0;
}
And these are my test cases:
3
xabcbayabbaz
abcbaabc
abcba
The code accepts the first string and gives the output. However, when I enter the next two strings, it just waits for more input. I tried giving input separately without the loop but that didn't work either. The compiler waits for more input infinitely.
I am putting my entire code here for reference.
#include <iostream>
#include <string.h>
using namespace std;
struct palindrome{
int start;
int end;
int strlength;
}s[20];
bool checkifpalindrome(string str)
{
string str1=str;
for(int i=0;i<str.length()/2;++i){
char temp=str1[i];
str1[i]=str1[str.length()-1-i];
str1[str.length()-1-i]=temp;
}
if(str1.compare(str)==0)
return true;
return false;
}
bool checkoverlap(int cur_pos,int prev_pos){
if((s[cur_pos].start>=s[prev_pos].start && s[cur_pos].start<=s[prev_pos].end)||
(s[cur_pos].end>=s[prev_pos].start && s[cur_pos].end<=s[prev_pos].end))
return true;
else
return false;
}
int findmax(int count){
int max = 0;
int pos = 0;
for(int i=0;i<count;++i){
if (s[i].strlength>max){
max = s[i].strlength;
pos = i;
}
}
return pos;
}
int findpalindrome(string str)
{
int sum=0;
int count=-1;
string str1;
for(int i=0;i<str.length();++i){
for(int j=1;j<str.length()-i+1;++j){
str1=str.substr(i,j+1);
if(checkifpalindrome(str1)){
count++;
s[count].start=i;
s[count].end=i+j;
s[count].strlength=str1.length();
}
}
}
int pos[2];
pos[0]=findmax(count);
sum+=s[pos[0]].strlength;
s[pos[0]].strlength=0;
pos[1]=findmax(count);
int i=0,n=10;
while(i<n){
if(s[pos[0]].strlength==str.length())
break;
else if(checkoverlap(pos[1],pos[0])){
s[pos[1]].strlength=0;
pos[1]=findmax(count);
continue;
}
else if(s[pos[1]].strlength==0)
break;
else{
sum+=s[pos[1]].strlength;
break;
}
i++;
}
return sum;
}
int main() {
int x=0,value=0;
cin>>x;
string str;
for(int i=0;i<x;++i){
cin>>str;
value = findpalindrome(str);
cout<<value<<endl;}
return 0;
}