您的位置:首页 > 其它

leetcode 5. Longest Palindromic Substring

2016-04-22 08:47 381 查看
//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 static void main(String[] args) {
String a = "abbaabba";
String result = longestPalindrome(a);
System.out.println(result);
}

public static String longestPalindrome(String s) {
String result = "";
int length = 0;
for(int i = 0;i<s.length();i++){
String temp1 = findString(s,i,i);				//奇数字符串寻找回文字符串
if(length<temp1.length()){
length = temp1.length();
result = temp1;
}
String temp2 = findString(s,i,i+1);				//偶数字符串寻找回文字符串
if(length<temp2.length()){
length = temp2.length();
result = temp2;
}
}
System.out.println(result);
return result;
}

//从中心向两侧扩展寻找回文字符串的函数
public static String findString(String str, int left, int right){
while(left>=0&&right<=str.length()-1&&str.charAt(left) == str.charAt(right)){
left--;
right++;
}
return str.substring(left+1, right);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: