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 };
有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
原文地址:https://www.cnblogs.com/mr-stn/p/9196718.html