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

leetcode 005 Longest Palindromic Substring(java)

时间:2016-01-15 20:02:14      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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"));
	}
	
}

  

 

leetcode 005 Longest Palindromic Substring(java)

标签:

原文地址:http://www.cnblogs.com/WillsCheng/p/5133956.html

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