kelvin
0
Q:

find all the palindrome substring in a given string

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

// expand in both directions of low and high to find all palindromes
void expand(string str, int low, int high, auto &set)
{
	// run till str[low.high] is a palindrome
	while (low >= 0 && high < str.length()
			&& str[low] == str[high])
	{
		// push all palindromes into the set
		set.insert(str.substr(low, high - low + 1));

		// expand in both directions
		low--, high++;
	}
}

// Function to find all unique palindromic substrings of given string
void allPalindromicSubstrings(string str)
{
	// create an empty set to store all unique palindromic substrings
	unordered_set<string> set;

	for (int i = 0; i < str.length(); i++)
	{
		// find all odd length palindrome with str[i] as mid point
		expand(str, i, i, set);

		// find all even length palindrome with str[i] and str[i+1] as
		// its mid points
		expand(str, i, i + 1, set);
	}

	// print all unique palindromic substrings
	for (auto i : set)
		cout << i << " ";
}

int main()
{
	string str = "google";

	allPalindromicSubstrings(str);

	return 0;
}
0
Initial Values : i = 0, j = n-1;
Given string 'str'

CountPS(i, j)
   
   // If length of string is 2 then we 
   // check both character are same or not 
   If (j == i+1)
      return str[i] == str[j]

   Else If str[i..j] is PALINDROME 
      // increment count by 1 and check for 
      // rest palindromic substring (i, j-1), (i+1, j)
      // remove common palindrome substring (i+1, j-1)
      return  countPS(i+1, j) + countPS(i, j-1) + 1 -
                                   countPS(i+1, j-1);

    Else // if NOT PALINDROME 
       // We check for rest palindromic substrings (i, j-1)
       // and (i+1, j)
       // remove common palindrome substring (i+1 , j-1)
       return  countPS(i+1, j) + countPS(i, j-1) - 
                             countPS(i+1 , j-1);

0

New to Communities?

Join the community