LeetCode:5. longest Palindrom substring
第一种方法:
Approach 4: Expand Around Center
In fact, we could solve it in O(n^2)O(n
2
) time using only constant space.
We observe that a palindrome mirrors around its center. Therefore, a palindrome can be expanded from its center, and there are only 2n - 12n−1 such centers.
You might be asking why there are 2n - 12n−1 but not nn centers? The reason is the center of a palindrome can be in between two letters. Such palindromes have even number of letters (such as “abba”) and its center are between the two 'b’s.
实现:
class Solution {
public:
string longestPalindrome(string s) {
int m = 0, start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandCenter(s, i, i);
int len2 = expandCenter(s, i, i + 1);
int len = max(len1, len2);
if (len > m) {
m = len;
start = i - (len - 1) / 2;
}
}
return s.substr(start, m);
}
int expandCenter(string s, int left, int right) {
while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
return right - left - 1;
}
};
Success
Details
Runtime: 40 ms, faster than 57.91% of C++ online submissions for Longest Palindromic Substring.
Memory Usage: 104 MB, less than 17.80% of C++ online submissions for Longest Palindromic Substring.
注意:对substr()函数的理解,第一个参数是start,第二个是size。
但是速度还是不够快,所以我决定学习一下动态规划的思想。
这是个很有启发性的博客:
https://blog.csdn.net/u013309870/article/details/75193592
过桥问题的理解可以参考这篇文章:https://blog.csdn.net/u014113686/article/details/82464635