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

    Example1:
        Input: "babad"
    
        Output: "bab"
    
        Note: "aba" is also a valid answer.
        
    Example2:
        Input: "cbbd"
    
        Output: "bb"
    

    思路

    • 最简单的思路,把所有的回文串都检查一遍,然后保存最长的
    • 怎么检查呢?
    • 回文串都是有一个对称中心的,所以现在,假设index=0为回文串的中心,然后向它的前和后扩展。这样遍历一遍可得到全部回文串。
    • 注意是相同字符的情况,如果字符连续相同,则不管它是出现奇数次还是偶数次都是回文的。
    • 注意判断边界条件

    代码

    • 时间复杂度 O(n) ? O(n^2) ? 我还真不知道。。
    class Solution {
    public:
        string longestPalindrome(string s) {
            int len = s.size();
            
            if(len <= 1) return s;
            
            string res;
            int max_size = -1, max_start = 0, i = 0, j = 0;
            int index = 0, size = 0;
            while(index < len){
                i = index;
                while(index + 1 < len){
                    if(s[index] == s[index + 1])
                        index++;
                    else break;
                }
                
                j = index;
                while(i - 1 >= 0 && j + 1 < len){
                    if(s[i - 1] == s[j + 1]){
                        i--;
                        j++;
                    }
                    else break;
                }
                
                size = j - i + 1;
                
                if(size > max_size){
                    max_size = size;
                    max_start = i;
                }
                
                index++;
            }
            
            res = s.substr(max_start, max_size);
            
            return res;
        }
    };
    
  • 相关阅读:
    Solution -「LOCAL」客星璀璨之夜
    Solution -「LOCAL」割海成路之日
    aaa
    wendang
    OSS架构
    MySQL事务
    1292分数和
    printf使用方法 (c++)
    1024与圆相关的计算
    Js 之echarts世界地图与汉化
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6804483.html
Copyright © 2011-2022 走看看