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

Longest Palindromic Substring

时间:2015-05-12 09:16:55      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public String longestPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return null;
        }
        
        String longest = s.substring(0, 1);
        for (int i = 0; i < s.length(); i++) {
            String tmp = helper(s, i, i);
            //get longest palindromic substring with one letter center i like aba
            if (tmp.length() > longest.length()) {
                longest = tmp;
            }
            
            //get longest palindromic substring with two letter, i, i+1 like abba
            tmp = helper(s, i, i+1);
            if (tmp.length() > longest.length()) {
                longest = tmp;
            }
        }
        return longest;
    }
    
    //given a center, one letter or two letter
    //return longest palindrome
    public String helper(String s, int begin, int end) {
        while (begin >= 0 && end <= s.length() - 1 && s.charAt(begin) == s.charAt(end)) {
            begin--;
            end++;
        }
        return s.substring(begin+1, end);
    }
}

 

Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4496339.html

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