5. Longest Palindromic Substring

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.

O(n^2)

public class Solution {
    public String longestPalindrome(String s) {
        String maxString = "";
        if(s.isEmpty() || s.length() == 1){
            return s;
        }
        for(int i = 0; i < s.length() -1; i++){
           String cur =  helper(i, i, s);
           if(cur.length() > maxString.length()){
               maxString = cur;
           }
           cur =  helper(i, i+1, s);
           if(cur.length() > maxString.length()){
               maxString = cur;
           }
           
        }
        return maxString;
    }
    public String helper(int left, int right, String s){
        while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
            left --;
            right ++;
        }
        return s.substring(left+1, right);
    }
}

  

原文地址:https://www.cnblogs.com/joannacode/p/5816570.html