Dada una string, la tarea es contar todas las substrings de palíndromo en una string dada.
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"
Acercarse:
- Tome las substrings de la string dada.
- Ahora compruebe si la substring es Palindrome o no.
- Si la substring es Palindrome, incremente el conteo en 1; de lo contrario, no se incrementa el conteo.
- Devuelve el recuento, ya que representa el número de substrings.
- Imprima y visualice en la consola.
Ejemplo:
Java
// Java Program to Find all palindromic sub-strings // of a given string // Importing input output classes import java.io.*; // Main class // To check for pallindromic sub-strings public class GFG { // Method 1 // To check for substring public static boolean check(String subS) { int size = subS.length(); // Iterating over string till midway to // check pallindromic behavior for (int i = 0; i < size / 2; i++) { if (subS.charAt(i) != subS.charAt(size - i - 1)) { // Non-pallindromic behavior return false; } } // Pallindromic behavior return true; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string String str = "MALAYALAM"; int count = 0; // Outer loop iterating over input string for (int i = 0; i < str.length(); i++) { // Inner loop iterating from current starting // character of outer loop current starting // character for (int j = i; j < str.length(); j++) { // Getting the substrings String subString = str.substring(i, j + 1); // Checking whether the substring is // pallindrome if (check(subString)) { // Increment the count only if // substring is pallindrome count++; } } } // Print and display the number of substrings that // are pallindromic System.out.println( "No.of palindromic substrings in the given string are " + count); } }
Producción
No.of palindromic substrings in the given string are 15
Publicación traducida automáticamente
Artículo escrito por ganiprabhakar y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA