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

leetcode--Longest Palindromic Substring

时间:2014-06-29 20:28:58      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:blog   java   c   for   leetcode   io   

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

public class Solution {
    public String longestPalindrome(String s) {
        if(s.length() < 2)
			return s;
		int len = s.length();
		String maxSub = "";
		int maxLen = 0;
		for(int i = 0; i < len; ++i){
			String tempOdd = expandPalindrome(s, i, i);
			if(maxLen < tempOdd.length()) {
				maxSub = tempOdd;
				maxLen = tempOdd.length();
			}
			
			if(i + 1 < len) {
				String tempEven = expandPalindrome(s, i , i + 1);
				if(maxLen < tempEven.length()) {
					maxSub = tempEven;
					maxLen = tempEven.length();
				}
			}
		}
		return maxSub;
    }
	
	private String expandPalindrome(String s, int left, int right){
		int len = s.length();
		while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
			--left;
			++right;
		}
		return s.substring(left + 1, right);
    }
}

  

leetcode--Longest Palindromic Substring,布布扣,bubuko.com

leetcode--Longest Palindromic Substring

标签:blog   java   c   for   leetcode   io   

原文地址:http://www.cnblogs.com/averillzheng/p/3814500.html

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