LeetCode(5)——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"

 

AC:

public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        
        int max = 0;
        int index = 0;
        
        int center = 0;
        int len = s.length();
        
        while (center < len) {
            int subLen;
            int left;
            int right;
            //奇數
            subLen = 1;
            left = center - 1;
            right = center + 1;
            while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                subLen += 2;
                left -= 1;
                right += 1;
            }
            
            if (subLen > max) {
                max = subLen;
                index = left + 1;
            }
            
            //偶數
            subLen = 0;
            left = center;
            right = center + 1;
            while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                subLen += 2;
                left -= 1;
                right += 1;
            }

            if (subLen > max) {
                max = subLen;
                index = left + 1;
            }
            
            center++;
        }
        
        return s.substring(index, index + max);
    }

還有種更高效的解法,馬拉車算法(Manacher),可以把複雜度降低到O(n)級別,有興趣可以搜一下。大部分人在短時間內是想不到這種方法來解的。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章