Longest Palindromic Substring

来源:互联网 发布:002175东方网络股票 编辑:程序博客网 时间:2024/06/06 03:38

题目: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.

也就是求最长回文子字符串。回文就是指从左到右和从右到左是相同的字符串。如abba,aba。

public static String longestPalindrome(String s) {    if(s.isEmpty())    return null;    if(s.length()==1)    return s;    String longest=s.substring(0,1);    for(int i=0;i<s.length();i++){    // get longest palindrome with center of i    String temp=helper(s, i, i);    if(temp.length()>longest.length())    longest=temp;    // get longest palindrome with center of i,i+1    temp=helper(s, i, i+1);    if(temp.length()>longest.length())    longest=temp;    }    return longest;    } // Given a center, either one letter or two letter, Find longest palindrome    public static String helper(String s,int start,int end){    while(start>=0&&end<s.length()&&s.charAt(start)==s.charAt(end)){    start--;    end++;    }    return s.substring(start+1,end);    }


0 0