1#include <iostream>
2#include <string>
3#include <unordered_set>
4using namespace std;
5
6// expand in both directions of low and high to find all palindromes
7void expand(string str, int low, int high, auto &set)
8{
9 // run till str[low.high] is a palindrome
10 while (low >= 0 && high < str.length()
11 && str[low] == str[high])
12 {
13 // push all palindromes into the set
14 set.insert(str.substr(low, high - low + 1));
15
16 // expand in both directions
17 low--, high++;
18 }
19}
20
21// Function to find all unique palindromic substrings of given string
22void allPalindromicSubstrings(string str)
23{
24 // create an empty set to store all unique palindromic substrings
25 unordered_set<string> set;
26
27 for (int i = 0; i < str.length(); i++)
28 {
29 // find all odd length palindrome with str[i] as mid point
30 expand(str, i, i, set);
31
32 // find all even length palindrome with str[i] and str[i+1] as
33 // its mid points
34 expand(str, i, i + 1, set);
35 }
36
37 // print all unique palindromic substrings
38 for (auto i : set)
39 cout << i << " ";
40}
41
42int main()
43{
44 string str = "google";
45
46 allPalindromicSubstrings(str);
47
48 return 0;
49}