[leetcode]5-Longest Palindromic Substring

Posted NovaCN

tags:

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

5. Longest Palindromic Substring

1)题目

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"

2)思路

遍历s, 判断每一位为中间位的最大回文子串。 比较即可。

3) 代码

public static String longestPalindrome(String s) {
        //指针p 记录遍历位置
        int p = 0;
        //最大长度
        int maxLen = 0;
        //最大子串
        String sr = "";

        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i=p+1) {
            p = i;
            int tempLenth = 0;
            String tempS = null;
            //结尾卫判断
            if (p + 1 == s.length()) {
                if (sr.length() >= 2)
                    return sr;
                //已经是最后一位
                return String.valueOf(chars[p]);

            }
            //非回文,指针往后走
            if (p + 2 < s.length() && chars[p + 1] != chars[p] && chars[p + 2] != chars[p]) {
                p++;
            }
            if (p +2 < s.length() && chars[p + 2] == chars[p]) {
                //奇回文
                int j = 1;
                while (p - j >= 0 && p + j + 2 <= s.length() - 1 && chars[p - j] == chars[p + 2 + j]) {
                    j++;
                }
                tempLenth = 2 * j + 1;
                tempS = s.substring(p - j + 1, p + j + 2);
                if (tempLenth > maxLen) {
                    maxLen = tempLenth;
                    sr = tempS;
                }

            }
            if (chars[p + 1] == chars[p]) {
                //偶回文
                int j = 1;
                while (p - j >= 0 && p + j + 1 <= s.length() - 1 && chars[p - j] == chars[p + j + 1]) {
                    j++;
                }
                tempLenth = 2 * j;
                tempS = s.substring(p - j + 1, p + j + 1);
                if (tempLenth > maxLen) {
                    maxLen = tempLenth;
                    sr = tempS;
                }
            }
        }
        return sr;
    }

4) 结果

时间复杂度:O(n^2)
空间复杂度:O(n)
耗时:

5) 调优



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

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

LeetCode题解 #5 Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

Leetcode #5. Longest Palindromic Substring

[leetcode][5] Longest Palindromic Substring