LeetCode Algorithm 05

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Tags: String

容易想到的思路(可以解但会超时):

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length();
        for(int n=len; n>=1; n--){
            for(int i=0; i<=len-n; i++){
                if(isPalin(s.substr(i,n))){
                    return s.substr(i,n);
                }
            }
        }
    }
    bool isPalin(string sub){
        int len = sub.length();
        for(int i=0,j=len-1; i<j; i++,j--){
            if(sub[i]!=sub[j])
                return false;
        }
        return true;
    }
};

更好的思路:

上述思路相当于先构建一系列子字符串,然后分析每个子串是否回文数,这样将会有非常多的组合,计算复杂度高。这种思路其实是收缩的思路。

如果我们从前往后遍历,每次遍历到一个字符便以之为中心看能向两边扩散多远,从而形成一些列子串,如果形成的子串长度大于result,则更新result。这种思路是扩散的思路。

此题其实与LeetCode Algorithm 03有类似之处,即都不能直接构造固定长度字符串然后判断是否合乎要求。正确的做法都是先设定一个子串的出发点(端点或中心点),然后尽可能增长直到不满足条件,形成子串,然后更新原有的局部最佳子串,最终形成全局最长子串。

c++代码:

 1 class Solution {
 2 public:
 3     string centerToOutside(string s, int left, int right){
 4         while(left>=0 && right<=s.length()-1 && s[left]==s[right]){
 5             left--;right++;
 6         }
 7         return s.substr(left+1, right-left-1);
 8     }
 9
10     string longestPalindrome(string s) {
11         int len = s.length();
12         if(len == 0){
13             return "";
14         }
15         string result = s.substr(0,1);
16         for(int i=0; i<len-1; i++){
17             string s1 = centerToOutside(s, i, i);
18             if(s1.length() > result.length()){
19                 result = s1;
20             }
21             string s2 = centerToOutside(s, i, i+1);
22             if(s2.length() > result.length()){
23                 result = s2;
24             }
25         }
26         return result;
27     }
28
29 };
时间: 2024-08-09 10:30:13

LeetCode Algorithm 05的相关文章

LeetCode Algorithm

原文出处:[LeetCode] 算法参考:[陈皓 coolshell] 3.Longest Substring Without Repeating Characters 3.Longest Substring Without Repeating Characters /********************************************************** ** 3.Longest Substring Without Repeating Characters ** G

Leetcode Algorithm No.241Different Ways to Add Parentheses

题目来自Leetcode Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. Example 1 Input: "2-1-1". ((2-1)-1) = 0 (2-(1-1)

LeetCode Algorithm 04

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Tags: Divide and Conquer, Array, Binary Search 分析: 对于数字个数k,如果k为奇数,则k个数的中位数为第(k/2+1)个:对

LeetCode Algorithm 07_Reverse Integer

Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought throug

LeetCode Algorithm 06

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I RAnd then read line by line: "PAHNAPLSIIG

LeetCode Algorithm 03

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest subst

LeetCode Algorithm 02

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 ->

LeetCode Algorithm 01

Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that

leetcode 算法 之 马拉松算法(Manacher&#39;s algorithm)(未完成)

马拉松算法:马拉松算法是用来计算一个字符串中最长的回文字符串(对称字符串,如aba abba). 首先,我们拿到一个字符串S,然后在S中的每个字符之间加#.例如:S="abcb" T="a#b#c#b" 我们T字符串的每一个T[i]向延伸d个字符 使得 T[i-d,i+d]是一个回文字符串.你会立刻发现,d就是以T[i]为中心的最长回文字符串的长度. 我们建立一个P数组,是的P数组的长度等于T的长度,每一个P[i]的值表示对应的T[i]为中心的最大回文字符串的长度.