zoukankan      html  css  js  c++  java
  • 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.

    Example 1:

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

    Example 2:

    Input: "cbbd"
    Output: "bb"

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    知道但是写不出来:

    extendPalindrome(s, i, i)扩展奇数长度,extendPalindrome(s, i, i + 1); 扩展偶数长度

     

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    [一句话思路]:

    定义lo, maxLen变量,从中间截断

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    改变low index 和maxlength index,字符串不是直接得来的,是从中切出来

    [复杂度]:Time complexity: O(n) Space complexity: O(1)

    [算法思想:迭代/递归/分治/贪心]:

    [关键模板化代码]:

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

     [是否头一次写此类driver funcion的代码] :

    class Solution {
        //ini
        int lo, maxLength;
        
        public String longestPalindrome(String s) {
            //cc: s.length() < 
            if (s == "" || s.length() == 0 || s.length() == 1) return s;
            
            //for loop in two cases
            for (int i = 0; i < s.length() - 1; i++) {
                extendPalindrome(s, i, i);
                extendPalindrome(s, i, i + 1);
            }
            
            //return substring
            return s.substring(lo, lo + maxLength);
        }
        
        public void extendPalindrome(String s, int k, int j) {
            //while loop 
            //k should always < s.length() since the index is from 0 to n -1
            while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
                j--;
                k++;
            }
            
            //renew the lo, maxLength;
            if (k - 1 - j > maxLength) {
                maxLength = k - 1 - j;
                lo = j + 1;
            }
        }
    }
    View Code

     [潜台词] :

     

  • 相关阅读:
    Cpp Singleton
    回溯法( Backtracking Algorithms ) :C语言Maze迷宫问题(自己实现)
    First wxWidgets Demo, wxWidgets简单示例
    copy contructor拷贝构造函数 (Copy Control)
    UPX (Ultimate Packer for eXecutables) 多平台可执行文件压缩
    wxWidgets Event Handling
    WxWidgets 安装与测试
    顺序查找 sequential find
    HDU1171 Big Event in HDU 背包
    HDU2091 水题
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9384823.html
Copyright © 2011-2022 走看看