Palindrome Counter | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

Problem Description

A palindrome is a string that reads the same from the left and from the right. For example, mom and tacocat are palindromes, as are any single character strings. Given a string, determine the number of its substrings that are palindromes. For example, the string is s = “tacocat”. Palindromic substrings are [‘t’, ‘a’, ‘c’, ‘o’, ‘c’, ‘a’, ‘t’, ‘coc’, ‘acoca’, ‘tacocat’]. There are 10 palindromic substrings.

Function Description

Complete the solution function in your editor. It should return an integer that represents the number of palindromic substrings in the given string.

Sample Input: “aaa”

Sample Output: 6

Explanation: There are 6 possible substrings of s: {“a”, “a”, “a”, “aa”, “aa”, “aaa”}. All of them are palindromes, so return 6.

package com.test;

/**
 * @author code.factory
 *
 */
public class PalindromeCounter {

	public static void main(String[] args) {
		System.out.println("Palindrom Counter: " + Solution("ABA"));
	}

	public static int Solution(String s) {
		int count = 0;
		for(int i=0; i<s.length(); i++) {
			for(int j=i; j<s.length(); j++) {
				System.out.println(i + " " + j + " " + s.substring(i, j+1) + " " + checkPalindrom(s.substring(i, j+1)));
				if(s.substring(i, j+1).equals(checkPalindrom(s.substring(i, j+1)))) {
					count++;
				}
			}
		}
		return count;
	}

	private static String checkPalindrom(String str) {
		String newStr = "";
		for(int i=str.length()-1; i>=0; i--) {
			newStr += str.charAt(i);
		}
		return newStr;
	}
}

Output:

Input: "ABA"

0 0 A A
0 1 AB BA
0 2 ABA ABA
1 1 B B
1 2 BA AB
2 2 A A
Palindrom Counter: 4

Input: "TACOCAT"

0 0 T T
0 1 TA AT
0 2 TAC CAT
0 3 TACO OCAT
0 4 TACOC COCAT
0 5 TACOCA ACOCAT
0 6 TACOCAT TACOCAT
1 1 A A
1 2 AC CA
1 3 ACO OCA
1 4 ACOC COCA
1 5 ACOCA ACOCA
1 6 ACOCAT TACOCA
2 2 C C
2 3 CO OC
2 4 COC COC
2 5 COCA ACOC
2 6 COCAT TACOC
3 3 O O
3 4 OC CO
3 5 OCA ACO
3 6 OCAT TACO
4 4 C C
4 5 CA AC
4 6 CAT TAC
5 5 A A
5 6 AT TA
6 6 T T
Palindrom Counter: 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s