码迷,mamicode.com
首页 > 其他好文 > 详细

5. Longest Palindromic Substring - Medium

时间:2019-01-25 11:34:43      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:遍历   function   tar   har   stp   mat   sub   you   example   

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"
 
M1: dp
dp[i][j]表示s.substring(i, j)是否是一个palindromic string
time: O(n^2), space: O(n^2)
 
M2: expand around corner
遍历s,对每一个可能的位置都用helper function check能否expand around corner并找出expand的长度。因为center可能在字母位置也可能在两个字母中间位置,对两个位置都要expand并找出较大的。最后更新一下start, end的位置,如果len > start - end
time: O(n^2), space: O(1)
class Solution {
    public String longestPalindrome(String s) {
        if(s == null || s.length() < 1) {
            return "";
        }
        int start = 0, end = 0;
        for(int i = 0; i < s.length(); i++) {
            int len1 = helper(s, i, i);
            int len2 = helper(s, i, i + 1);
            int len = Math.max(len1, len2);
            if(len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }
    
    private int helper(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;
    }
}
 
M3: Manacher‘s Algorithm
time: O(n), space: O()
 

5. Longest Palindromic Substring - Medium

标签:遍历   function   tar   har   stp   mat   sub   you   example   

原文地址:https://www.cnblogs.com/fatttcat/p/10317768.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!