Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Java program to print all palindrome strings in the given input.
For Example, if the input is “ABABBASSGGAASDGBDSRACECAR”, the program will print all palindromes in it as below:
“ABA”, “BAB”, “ABBA”, “BB”, “SS”, “GG”, “AA”, “RACECAR”, “ACECA”, “CEC”
Here is the Java Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package com.sample.clearurdoubt; import java.time.Instant; public class PalindromeFinder { public static void main(String[] args) throws InterruptedException{ String input = "ABABBASSGGAASDGBDSRACECAR"; System.out.println("Palindromes in the given input(" + input + ")"); Long start = Instant.now().toEpochMilli(); supplyInputs(input); Long end = Instant.now().toEpochMilli(); System.out.println("TOTAL TIME: " + (end - start) + " milliseconds."); } private static void supplyInputs(String input) { int length = input.length(); for(int start = 0; start <= length-2; start++ ) { for(int end = length; Math.abs(start-end) >= 2; end--) { printIfPalindrome(input.substring(start, end)); } } } private static void printIfPalindrome(String input) { int length = input.length(); boolean isPalindrome = true; for(int i = 0; i <= (length-1)/2; i++) { if(input.charAt(i) != input.charAt(length-1-i)) { isPalindrome = false; break; } } if(isPalindrome) { System.out.println(input); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 |
Palindromes in the given input(ABABBASSGGAASDGBDSRACECAR) ABA BAB ABBA BB SS GG AA RACECAR ACECA CEC TOTAL TIME: 1 milliseconds. |
Happy Learning. 🙂
Please leave a reply in case of any queries.