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

19.1.20 [LeetCode 5]Longest Palindromic Substring

时间:2019-01-20 15:07:08      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:open   onclick   回文   分享   out   als   9.1   splay   开始   

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 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         int leng = 0, size = s.length();
 5         string p;
 6         for (int i = 0; i<size; i++) {
 7             int l = 1;
 8             int S = i, E = i;
 9             while (S > 0 && E < size - 1 && s[S - 1] == s[E + 1]) {
10                 S--, E++;
11                 l += 2;
12             }
13             if (l > leng) {
14                 p = s.substr(S, l);
15                 leng = l;
16             }
17         }
18         for (int i = 0; i < size-1; i++) {
19             if (i + 1 > size - 1)break;
20             int l = 0;
21             int S = i+1, E = i;
22             while (S > 0 && E < size - 1 && s[S - 1] == s[E + 1]) {
23                 S--, E++;
24                 l += 2;
25             }
26             if (l > leng) {
27                 p = s.substr(S, l);
28                 leng = l;
29             }
30         }
31         return p;
32     }
33 };
View Code

从大小为1或2的回文串开始扩展

19.1.20 [LeetCode 5]Longest Palindromic Substring

标签:open   onclick   回文   分享   out   als   9.1   splay   开始   

原文地址:https://www.cnblogs.com/yalphait/p/10294749.html

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