题目来源leetcode
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"
数据规模最大只有1000,所以朴素算法的时间复杂度O(n^2)应该可以搞定。于是写了下面的代码:
class Solution {
public:
bool isPalindrome(string s, int begin, int end) {
int i = begin, j = end;
while (i < j && i <= end && j >= begin) {
if(s[i] != s[j]) {
return false;
}
i ++;
j --;
}
return true;
}
string longestPalindrome(string s) {
int max_len = 0;
string str;
if( s.size() <= 1 ) {
return (s);
}
for(int i = 0; i < s.size() - 1; i ++) {
for(int j = i + 1; j < s.size(); j ++) {
if((j - i + 1) > max_len && isPalindrome(s, i, j)) {
max_len = j - i + 1;
str = s.substr(i, max_len);
}
}
}
if(max_len == 0) {
str = s.substr(0, 1);
}
return str;
}
};
令人意外的是Memory Limit Exceeded,内存竟然超了。所以修改一下,判断是否为回文的函数改成传引用。甚至把中间变量str也去掉,改成记录一下位置(begin_pos)
class Solution {
public:
bool isPalindrome(string &s, int begin, int end) {
int i = begin, j = end;
while (i < j && i <= end && j >= begin) {
if(s[i] != s[j]) {
return false;
}
i ++;
j --;
}
return true;
}
string longestPalindrome(string s) {
int max_len = 0;
int begin_pos = 0;
if( s.size() <= 1 ) {
return (s);
}
for(int i = 0; i < s.size() - 1; i ++) {
for(int j = i + 1; j < s.size(); j ++) {
if((j - i + 1) > max_len && isPalindrome(s, i, j)) {
max_len = j - i + 1;
begin_pos = i;
}
}
}
if(max_len == 0) {
begin_pos = 0;
max_len = 1;
}
return s.substr(begin_pos, max_len);
}
};
最终Pass.
时间上肯定比较慢,但没想到空间占用这么小:
Runtime: 220 ms, faster than 22.53% of C++ online submissions for Longest Palindromic Substring.
Memory Usage: 8.9 MB, less than 99.30% of C++ online submissions for Longest Palindromic Substring.