leetcode 5. Longest Palindromic Substring

Posted 巴蜀小小生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 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"

 1 #include<cmath>
 2 class Solution {
 3 public:
 4     string longestPalindrome(string s) {
 5         int  start=0, end=0, i ;
 6         for(i=0; i<s.size(); i++){
 7             int len1=sub_string_length(s, i, i);
 8             int len2=sub_string_length(s, i, i+1);
 9             int len = len1>len2 ? len1 : len2;
10             if(len>end-start+1){
11                 start=i-(len-1)/2;
12                 end=i+len/2;
13             }
14         }
15         return s.substr(start, end-start+1);
16     }
17     
18     int sub_string_length(string s, int left, int right){
19         int l=left, r=right;
20         while(l>=0 && r<s.size() && s[l]==s[r]){
21             l--;
22             r++;
23         }
24         return r-l-1;
25     }
26 };

 



以上是关于leetcode 5. Longest Palindromic Substring的主要内容,如果未能解决你的问题,请参考以下文章

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring

LeetCode题解 #5 Longest Palindromic Substring

[LeetCode] 5 Longest Palindromic Substring

Leetcode #5. Longest Palindromic Substring

LeetCode 5_Longest Palindromic Substring