5 Longest Palindromic Substring

Given a strings, find the longest palindromic substring ins. You may assume that the maximum length ofsis 1000.

Example 1:

Input:
 "babad"

Output:
 "bab"

Note:
 "aba" is also a valid answer.

Example 2:

Input:
 "cbbd"

Output:
 "bb"

Solution)

class Solution {
    public int findPalindromeLength(String s, int left, int right) {
        int L = left, R = right;
        while(L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
            L--; R++;
        }
        return R-L-1;
    }
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) return "";
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len = Math.max(findPalindromeLength(s, i, i), findPalindromeLength(s, i, i+1));
            if (len > end - start + 1) {
                start = i - (len -1)/2;
                end = i + len/2;
            }
        }
        return s.substring(start, end+1);
    }
}

results matching ""

    No results matching ""