码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 5. Longest Palindromic Substring (java)

时间:2020-03-12 14:14:41      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:lin   rom   middle   har   substr   ++   from   leetcode   char   

class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() < 1) return "";
        
        int start = 0;
        int end = 0;
        
        for (int i = 0; i < s.length(); i++) {
            int len1 = expandFromMiddle(s, i, i);
            int len2 = expandFromMiddle(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 expandFromMiddle(String s, int left, int right) {
        if (s == null || left > right) return 0;
        
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        
        return right - left - 1;
    }
}

  

leetcode 5. Longest Palindromic Substring (java)

标签:lin   rom   middle   har   substr   ++   from   leetcode   char   

原文地址:https://www.cnblogs.com/eniac-inner/p/12468883.html

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