Posts Palindromic Substrings
Post
Cancel

Palindromic Substrings

This question is part of NeetCode150 series.

Problem Description

Given a string s, return the longest palindromic substring in s.

leetcode

Solution

This question is similar to: Longest Palindrome SubString

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
class Solution {
    
    public int countSubstrings(String s) {
        
        int n = s.length();
        int count = 0;

        for(int i=0; i<n; i++){

            //odd palindrome
            int oddCount = countPalindromes(s, i, i);
            
            //even palindrome
            int evenCount = countPalindromes(s, i, i+1);

            count = count + oddCount + evenCount;

        }

        return count;

    }

    public int countPalindromes(String s, int start, int end){

        int count = 0;
        
        int l = start;
        int r = end;

        while(l>=0 && r<s.length() && s.charAt(l) == s.charAt(r)){
            count++;
            l--;
            r++;
        }
        
        return count;

    }

}
This post is licensed under CC BY 4.0 by the author.