all palindromic substrings in a string code example
Example 1: reads the string in then determines if the string is a palindrome.
#include <iostream>
using namespace std;
bool isPalindrome(string str)
{
int low = 0;
int high = str.length() - 1;
while (low < high)
{
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
int main()
{
string str = "XYXYX";
if (isPalindrome(str))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}
Example 2: find all the palindrome substring in a given string
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
void expand(string str, int low, int high, auto &set)
{
while (low >= 0 && high < str.length()
&& str[low] == str[high])
{
set.insert(str.substr(low, high - low + 1));
low--, high++;
}
}
void allPalindromicSubstrings(string str)
{
unordered_set<string> set;
for (int i = 0; i < str.length(); i++)
{
expand(str, i, i, set);
expand(str, i, i + 1, set);
}
for (auto i : set)
cout << i << " ";
}
int main()
{
string str = "google";
allPalindromicSubstrings(str);
return 0;
}
Example 3: reads the string in then determines if the string is a palindrome.
#include <iostream>
using namespace std;
bool isPalindrome(string str, int low, int high)
{
if (low >= high)
return true;
if (str[low] != str[high])
return false;
return isPalindrome(str, low + 1, high - 1);
}
int main()
{
string str = "XYBYBYX";
int len = str.length();
if (isPalindrome(str, 0, len - 1))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}