Posts Longest Palindromic Substring
Post
Cancel

Longest Palindromic Substring

This question is part of NeetCode150 series.

Problem Description

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

leetcode

Solution

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
class Solution {

    //Time complexity: O(n^2)
    public String longestPalindrome(String s) {

        String ans = "";

        //At every index, check for longest palindrome substring
        for(int i=0; i<s.length(); i++){

            //odd length
            String oddString = palindromeHelper(s, i, i);
            if(oddString.length() > ans.length()){
                ans = oddString;
            }

            //even length
            String evenString = palindromeHelper(s, i, i+1);
            if(evenString.length() > ans.length()){
                ans = evenString;
            }

        }

        return ans;

    }

    public String palindromeHelper(String s, int l, int r){

        int start = -1;
        int end = -1;

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

        if(start == -1) return "";

        return s.substring(l+1, r);

    }

}

Further Reading: Manacher’s algorithm | O(n) solution

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