欢迎找我内推微软

[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:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example:

Input: "cbbd"

Output: "bb"


思路很简单:遍历字符串,找出以每个字符为中间字符的最长的回文串,再次遍历字符,找出以两个重复字符为中间字符的最长的字符串,从而得到字符串 s 的最长回文子串。

以下是我的代码,其中再确认中间字符时寻找最长回文串的代码重复了两次,也可以独立出一个函数来调用:
class Solution {
public:
    string longestPalindrome(string s) {
        int pos = 0, left = 0, right = 0, len = s.size();
        string result = "";
        while (pos < len) {
            while (1) {
                if (s[left] != s[right]) break;
                string tmp = s.substr(left, right - left + 1);
                if (tmp.size() > result.size()) result = tmp;
                if (--left < 0) break;
                if (++right >= len) break;
            }
            pos++;
            left = pos, right = pos;
        }
        for (int i = 0; i < len - 1; i++) {
            if (s[i] == s[i+1]) {
                left = i, right = i+1;
                while (1) {
                    if (s[left] != s[right]) break;
                    string tmp = s.substr(left, right - left + 1);
                    if (tmp.size() > result.size()) result = tmp;
                    if (--left < 0) break;
                    if (++right >= len) break;
                }
            }
        }
        return result;
    }
};

 




posted @ 2017-10-11 16:53  zmj97  阅读(125)  评论(0编辑  收藏  举报
欢迎找我内推微软