//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);
}
}
leetcode 5. Longest Palindromic Substring
最新推荐文章于 2024-09-21 10:02:17 发布