Problem · String

Palindrome Counter

Learn this problem
MediumGoldman SachsINTERNFULLTIMEOA

Problem statement

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.

Function

countPalindromes(s: String) → int

Complete the function countPalindromes in the editor.

countPalindromes has the following parameter:

  1. string s: the string to analyze

Returns

int: an integer that represents the number of palindromic substrings in the given string

Examples

Example 1

s = "tacocat"return = 10
Palindromic substrings are ['t', 'a', 'c', 'o', 'c', 'a', 't', 'coc', 'acoca', 'tacocat']. There are 10 palindromic substrings.

Example 2

s = "aaa"return = 6
There are 6 possible substrings of s: {'a', 'a', 'a', 'aa', 'aa', 'aaa'}. All of them are palindromes, so return 6.

Example 3

s = "abccba"return = 9
There are 21 possible substrings of s, the following 9 of which are palindromes: {'a', 'a', 'b', 'b', 'c', 'c', 'cc', 'bccb', 'abccba'}.

Example 4

s = "daata"return = 7
There are 15 possible substrings of s, the following 7 of which are palindromes: {'a', 'a', 'a', 'aa', 'ata', 'd', 't'}.

Constraints

1 ≤ |s| ≤ 5 x 103
each character of s, s[i] ∈ ['a'-'z'].

More Goldman Sachs problems

drafts saved locally
public int countPalindromes(String s) {
  // write your code here
}
s"tacocat"
expected10
checking account