zoukankan      html  css  js  c++  java
  • [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) 调优

  • 相关阅读:
    如何提升程序员的工作效率?
    MacOS 上网络故障诊断
    阅读混淆过的Android代码的确不易
    复旦投毒案落下帷幕
    正确把握深度和广度
    Freemarker的数据模型使用
    xilink se14.7 win10闪退
    浅谈 pid的原理与差异
    win10系统激活
    stm8 同时使用dac和adc 采集异常,电平异常
  • 原文地址:https://www.cnblogs.com/novaCN/p/10328050.html
Copyright © 2011-2022 走看看