The code works for chararcter array but it doesn’t work if I use string. Can you please explain why?
Is Palindrome problem
In this question it is specifically mentioned that you have to take array to store the inputs that is why it is showing wrong answer when you use string. But it will give correct output in your own compiler if you change the argument from char s[] to string s and in main you replace char s[n] to string s.
In other compiler also it’s not working.
Also there isn’t any editorial as well for any of the problems
#include
#include
using namespace std;
bool checkPalindrome(string s,int i,int j){
if(i==j)
return true;
if(s[i]!=s[j])
return false;
if((j-i)==1 && s[i]==s[j])
return true;
return checkPalindrome(s,i+1,j-1);
}
int main() {
string s="";
int n;
cin >> n;
//char s[n];
for(int i=0;i<n;i++){
char st;
cin >> st;
s=s+st;
}
int i=0,j=n-1;
if(checkPalindrome(s,i,j))
cout << “true”;
else
cout << “false”;
return 0;
}
it works fine in all compiler
#include
#include
using namespace std;
bool checkPalindrome(string s,int i,int j){
cout << s[i] << " "<< s[j] << endl;
if(i==j)
return true;
if(s[i]!=s[j])
return false;
if((j-i)==1 && s[i]==s[j])
return true;
return checkPalindrome(s,i+1,j-1);
}
int main() {
string s;
int n;
cin >> n;
//char s[n];
for(int i=0;i<n;i++)
cin >> s[i];
int i=0,j=n-1;
if(checkPalindrome(s,i,j))
cout << “true”;
else
cout << “false”;
return 0;
}
Is anything wrong in above code?
Yes in case of string you can not take input character by character … instead you have to take another character as input and append it to the original string. cin>>s[i] is not correct. Just for your understanding after taking input as cin>>s[i] try to cout the string s as cout<<s<<endl; . It will not output anything this why for every case you were getting false as output.
Ok, I understood that. But one more thing if in my checkPalindrome function while declaring if I write string& s instead of string s the code works fine. How is that happening?
This is because when you are taking string& s it is using the location of string s. and while you are inputing s[i] then the value is stored in the location of s[i] hence you are able to access all the elements of s in the function. But if you don’t use string& s then the function gets an empty string and that is why it prints false for every test case.
okay. Thanks