【Leetcode】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, and there exists one unique longest palindromic substring.

以每个字符为中心,向两侧拓展,找最长回文子串。

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         int n = s.size();
 5         int start = 0, step = 0, max_len = 0;
 6         for (int k = 0; k < n; ++k) {
 7             step = 0;
 8             while (k - step - 1 >= 0 && k + step + 1 < n && s[k - step - 1] == s[k + step + 1]) {
 9                 ++step;
10             }
11             if (2 * step + 1> max_len) {
12                 max_len = 2 * step + 1;
13                 start = k - step;
14             }
15             step = 0;
16             while (k + step + 1 < n && k - step >= 0 && s[k + step + 1] == s[k - step]) {
17                 ++step;
18             }
19             if (2 * step > max_len) {
20                 max_len = 2 * step;
21                 start = k - step + 1;
22             }
23         }
24         return s.substr(start, max_len);
25     }
26 };

 

posted @ 2014-10-06 22:48  小菜刷题史  阅读(135)  评论(0编辑  收藏  举报