[LeetCode 解题报告]005.Longest Palindromic Substring

Description:

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"

思想:详细见[编程之美-07]最长回文串 只是将原来打印长度,改变为打印该字符串。


class Solution {
public:
    string longestPalindrome(string s) {
        if(s.length() == 0)
            return "";
        int curStart, maxStart;
        int curLength = 0, maxLength = 0;
        for(int i = 0; i < s.length(); i ++) {
            for(int j = 0; i-j >= 0 && i+j < s.length(); j ++) {
                if(s[i-j] != s[i+j])
                    break;
                curLength = j*2 + 1;
                curStart = i-j;
            }
          
            if(curLength > maxLength) {
                
                maxLength = curLength;
                maxStart = curStart;
            }
            
            for(int j = 0; i-j >= 0 && i+j < s.length()-1; j ++) {
                if(s[i-j] != s[i+j+1])
                    break;
                curLength = j*2 + 2;
                curStart = i-j;
            }
            
            if(curLength > maxLength) {
                maxLength = curLength;
                maxStart = curStart;
            }
        }
        
        return s.substr(maxStart, maxLength);
    }
};




你可能感兴趣的:(LeetCode,解题报告,leetcode)