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) 调优

  • 相关阅读:
    vue 同页面不同参数
    vue的data用到this问题
    vue轮播,不是只有左右切换的,还有只切换src的
    vue页面高度填充,不出现滚动条
    WdatePicker做出onchange效果
    总结最近移动端遇到的坑(auto-size + zepto)
    react
    ES6-set && 数组剔重
    [置顶] Jquery easyui+Jsonp+asp.net+翻页 事件版
    扩展Jquery easyui的validator插件
  • 原文地址:https://www.cnblogs.com/novaCN/p/10328050.html
Copyright © 2011-2022 走看看