Leetcode 之 Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.

Example 2:

Input: “cbbd”
Output: “bb”

Answer:

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) return "";
        char[] chars = s.toCharArray();
        int start = 0;
        int end = 0;
        int maxLen = 0;
        for (int i = 0; i < chars.length; i++) {
            int lenLeft = getLen1(chars,i);
            int lemRight = getLen2(chars,i);
            int len = Math.max(lenLeft,lemRight);
            if(len>maxLen){
                maxLen = len;
                if(len == lenLeft){
                    start = i-(len/2);
                    end = i + (len/2);
                }else {
                    start = i - (len/2 - 1);
                    end = i+(len/2);
                }

            }
        }
        return s.substring(start,end+1);
    }

    /**
     * 以字母为对称中心
     * @param chars
     * @param mid
     * @return
     */
    public int getLen1(char[] chars,int mid){
        int left = mid;
        int right = mid;
        while (left >= 0 && right= 0 && right

你可能感兴趣的:(Leetcode,Java,基础,算法,Leetcode)