5. Longest Palindromic Substring

Posted 鱼与海洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

  

以上是关于5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 5. Longest Palindromic Substring

5. Longest Palindromic Substring - Unsolved

5. Longest Palindromic Substring

5. Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

5. Longest Palindromic Substring