Hello, everyone. I need some help with a C++ code I am writing.
So we have a string (for example: antnaoŃantnnff)
And what I have to do is to find and print all of its substrings which
are palindromes and their quantity. For example for "antnaocantnnff" the output should look like:
antna > 1 time
ntn > 2 times
nn > 1 time
ff > 1 time
Single letters are not considered palindromes, and also there is a restriction that I shouldn't use string class, and instead of it I need use char array (also two-dimensional). I have written a function for palindrome:
bool isPalindrome(char s[100])
{
int n = strlen(s);
if(n == 1) return 0;
int i;
for(i = 0; i < n/2; i++)
if(s[i] != s[n-1-i]) break;
if(i < n/2) return 0;
else return 1;
}
I think here I need to use two-dimensional char array where to save all the substrings and check for every single of it if it is a palindrome. But I haven't worked with two-dimensional char arrays before and I don't know how to accomplish this idea. Also, I need to count the palindromes and that confuses me a lot since a single counter won't help. I will be very grateful if you help me.
Here's one approach. Go through the string and see if each character is the middle of a three character palindrome. If it is then print it out and increment your counter. Then, if it was the middle of a 3-character palindrome, check to see if it's middle of a 4-character palindrome, etc.
Hmm. This method will make the output slightly different from what you've shown. It will show ntn, then antna. Is that okay?
Once this works, you can add code to check if each character is just left of the center of a two-character palindrome. If so then print it out and see if it's also next to the center of a 4-character palindrome, etc.
When checking if a character is the center of a palindrome, be sure to do some bounds checking so you aren't looking past the beginning or end of the string.