Java Program to Find All Palindromic Sub-Strings of a String
Last Updated :
03 Aug, 2022
Given a string, the task is to count all palindrome substring in a given string.
Input : aba
Output : 4
Explanation : All palindrome substring are : "aba" , "a" , "b", "a"
Input : TENET
Output : 7
Explanation : All palindrome sub-string are : "T" , "E" , "N", "E", "T" , "ENE" , "TENET"
Approach:
- Take the substrings from the given string.
- Now check whether the substring is Palindrome or not.
- If the substring is Palindrome increment the count by 1 else if not count is not incremented.
- Return the count as it represents the number of substrings.
- Print and display on the console.
Example:
Java
import java.io.*;
public class GFG {
public static boolean check(String subS)
{
int size = subS.length();
for ( int i = 0 ; i < size / 2 ; i++) {
if (subS.charAt(i)
!= subS.charAt(size - i - 1 )) {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
String str = "MALAYALAM" ;
int count = 0 ;
for ( int i = 0 ; i < str.length(); i++) {
for ( int j = i; j < str.length(); j++) {
String subString = str.substring(i, j + 1 );
if (check(subString)) {
count++;
}
}
}
System.out.println(
"No.of palindromic substrings in the given string are "
+ count);
}
}
|
Output
No.of palindromic substrings in the given string are 15
Share your thoughts in the comments
Please Login to comment...