return all palindromes in a string code example
Example 1: Java program to check palindrome string using recursion
import java.util.Scanner;
public class RecursivePalindromeJava
{
public static boolean checkPalindrome(String str)
{
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length() - 1))
return checkPalindrome(str.substring(1, str.length() - 1));
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string : ");
String strInput = sc.nextLine();
if(checkPalindrome(strInput))
{
System.out.println(strInput + " is palindrome");
}
else
{
System.out.println(strInput + " not a palindrome");
}
sc.close();
}
}
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;
}