LeetCode 5: 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 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

描述:

给定字符串s,查找s的最长回文子串。

假设字符串s的最大长度为1000.

示例1:

输入: “babad”
输出: "bab"
注意:“aba”也是有效的答案

示例2:

输入:“cbbd”
输出: “bb”

方法一:暴力破解

首先,明确回文的概念。“回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。

遍历字符串s的每一个子串,并判断该子字符串是否为回文。

class Solution {
public:
    string longestPalindrome(string s) {
        int len = s.length();
        string str;
        int maxLen = 0;
        if(len == 0) return s;
        for(int i = 0; i < len; i++) {
            for(int j = i + 1; j <= len; j++) {
                int len = palindromeLen(s, i, j);
                if(len >= maxLen) {
                    maxLen = len;
                    str = s.substr(i, j - i);
                }
            }
        }
        return str;
    }
    
    int palindromeLen(string str, int start, int end) {
        int s = start;
        int e = end - 1;
        while(s <= e) {
            if(str[s++] != str[e--])
                return 0;
        }
        return end - start;
    }
};

  该方法的时间复杂度为O(n3),空间复杂度为O(n)。

猜你喜欢

转载自www.cnblogs.com/alpaca/p/9476395.html