Longest Palindromic Substring(最长回文子串)

Posted wkcode

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Palindromic Substring(最长回文子串)相关的知识,希望对你有一定的参考价值。

Description:

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

1,暴力法

  判断字符串s的所有子串a是否为回文字符串,如果是,则返回字符串a与其长度l。最终返回长度最长的回文子串。

class Solution {
    public String longestPalindrome(String s) {
        String s1;
        String st = null;
        int maxLenrth = 0;
        if (s.length() == 1 || s.length() == 0) {
            return s;
        }else {
            for (int i = 0; i < s.length(); i++) {
                for (int j = i; j < s.length(); j++) {
                    s1 = s.substring(i, j+1);
                    if (isHw(s1)>maxLenrth) {
                        maxLenrth = isHw(s1);
                        st = s1;
                    }
                }
            }
            return st;
        }
    }
    
  //判断是否为回文 是返回其长度 否返回0
public int isHw(String s){ for (int i = 0; i < s.length()/2; i++) { if (s.charAt(i) != s.charAt(s.length()-i-1)) { return 0; } } return s.length(); } }

 2,...

 


以上是关于Longest Palindromic Substring(最长回文子串)的主要内容,如果未能解决你的问题,请参考以下文章

Longest Palindromic Substring

5. Longest Palindromic Substring

[Leetcode]Longest Palindromic Substring

LeetCode:Longest Palindromic Substring

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring