码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 5. Longest Palindromic Substring

时间:2018-06-18 23:47:35      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:--   nbsp   TE   pre   imu   longest   span   substr   max   

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

标签:--   nbsp   TE   pre   imu   longest   span   substr   max   

原文地址:https://www.cnblogs.com/mr-stn/p/9196718.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!