I need help debugging my code. What I want my code to do is to find the length of the largest palindrome in a string. A palindrome is something that will read the same forwards and backwards. Ex: bob or abccba.
Sample Input:
abcxyzzyx
Sample Output:
6
Right now my code can compile, but it will just spit out "0" for odd numbered strings, and will just output nothing and give an error for even numbered strings.
#include <iostream>
#include <string>
usingnamespace std;
int main(){
string s;
int n = 1, a = 0;
cin >> s;
if (s.length() %2 != 0) {
for (int i = 0; i < s.length(); i++) {
while (i != s.length() && s[i-n] == s[i+n]) {
n++;
if (n >= a) {
a = n *2 +1;
}
n = 0;
}
}
}
else {
for (int k = 0; k < s.length(); k++) {
while (k != s.length() && s[k-n] == s[k+n+1]) {
n++;
if (n >= a) {
a = n *2 +1;
}
n = 0;
}
}
}
cout << a;
cin.get();
return 0;
}
Thanks for reading.
Edit: I realized that whether the string's length is odd or even doesn't matter, only the palindrome's length matters.
Here's a revised version of the code that still will give errors and I don't know why:
#include <iostream>
#include <string>
usingnamespace std;
int main(){
string s;
int n = 1, a = 0;
cin >> s;
for (int i = 0; i < s.length(); i++) {
while (i != s.length() && s[i-n] == s[i+n] || s[i-n] == s[i+n+1]) {
n++;
if (n >= a) {
a = n *2 +1;
}
n = 0;
}
}
cout << a;
cin.get();
return 0;
}