leetcode 005 Longest Palindromic Substring(java)

5. Longest Palindromic Substring

My Submissions
Total Accepted: 87802 Total Submissions: 399054 Difficulty: Medium

 

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.

 

Subscribe to see which companies asked this question

 

题解:找一个字符串的最大回文串

以每个字母为中心,向两面扫。走一遍即可

 

import java.awt.print.Printable;


public class Solution {
	
	public static String longestPalindrome(String s) {
	String longestpalindrome=null;
	String tmp=null;
	int maxlen=0;
	
	if(s.length()==1)
		return s;
	
	for(int i=0;i<s.length();i++){
		tmp=getPalindrome(s, i, i);
		if(maxlen<tmp.length()){
			longestpalindrome=tmp;
			maxlen=tmp.length();
		}
		tmp=getPalindrome(s, i-1, i);
		if(maxlen<tmp.length()){
			longestpalindrome=tmp;
			maxlen=tmp.length();
		}
		
	}
	
	return longestpalindrome;
    }
	
	
	public static String getPalindrome(String s,int begin,int end) {
		while(begin>=0&&end<s.length()&&s.charAt(begin)==s.charAt(end)){
			begin--;
			end++;
		}
		return s.substring(begin+1, end);
	}
	
	public static void main(String[] args) {
		System.out.println(longestPalindrome("bb"));
	}
	
}

  

 

posted on 2016-01-15 17:59  ArcherCheng  阅读(171)  评论(0编辑  收藏  举报