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) {
String str = "";
int midIndex = 0 ;
int num = 0 ;
boolean isOnly = false;
for(int i = 0;i<s.length()-1;i++){
if(s.length()-1 - i < num){
break;
}else{
if(s.charAt(1+i) == s.charAt(i)){
int j = 1;
while(i-j>=0&&i+j+1<s.length()&&s.charAt(i-j) == s.charAt(i+j+1)){
j++;
}
if(num < j){
num = j;
midIndex = i;
isOnly = false;
}
}
if(i!= 0&&s.charAt(1+i) == s.charAt(i-1)){
int j = 1 ;
while(i-j>=0&&i+j<s.length()&&s.charAt(i+j) == s.charAt(i-j)){
j++;
}
j--;
if(num <= j){
num = j;
midIndex = i;
isOnly = true;
}
}
}
}
if(num ==0){
str = s.charAt(0)+"";
}else if(isOnly){
str = s.substring(midIndex - num, midIndex + num+1);
}else{
str = s.substring(midIndex- num+1,midIndex +num +1) ;
}
return str;
}
}
Longest Palindromic Substring
猜你喜欢
转载自plan454.iteye.com/blog/2185513
今日推荐
周排行