LeetCode -- Longest Palindromic Substring
2013-09-05 15:21
246 查看
链接:http://leetcode.com/onlinejudge#question_5
原题:
Given a string S,
find the longest palindromic substring in S.
You may assume that the maximum length of S is
1000, and there exists one unique longest palindromic substring.
思路:之前,我都是用O(n^2)做的,这回尝试一下用O(n)时间做一下,当然,方法是别人想出来的,呵呵。
请参考:http://www.felix021.com/blog/read.php?2040
真是算法无止境啊,这碗水很深。
代码:
原题:
Given a string S,
find the longest palindromic substring in S.
You may assume that the maximum length of S is
1000, and there exists one unique longest palindromic substring.
思路:之前,我都是用O(n^2)做的,这回尝试一下用O(n)时间做一下,当然,方法是别人想出来的,呵呵。
请参考:http://www.felix021.com/blog/read.php?2040
真是算法无止境啊,这碗水很深。
代码:
class Solution { public: string longestPalindrome(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.size() == 0) return ""; string str = "#"; for (int i=0; i<s.size(); i++) { str.append(1, s[i]); str.append(1, '#'); } vector<int> state(str.size()); state[0] = 1; int center = 0; int rBorder = center + state[0]; for (int i=1; i<str.size(); i++) { int j = 2 * center - i; if (j < 0) { state[i] = 1; int n = 1; while (i-n >= 0 && i+n < str.size() && str[i-n] == str[i+n]) n++; state[i] += n - 1; } else { if (rBorder - i > state[j]) state[i] = state[j]; else { state[i] = rBorder - i; int n = rBorder - i; while (i-n >= 0 && i+n < str.size() && str[i-n] == str[i+n]) { n++; state[i]++; } } } if (i + state[i] > rBorder) { rBorder = i + state[i]; center = i; } } int maxLength = 1; int maxCenter = 0; for (int i=0; i<state.size(); i++) { if (state[i] > maxLength) { maxLength = state[i]; maxCenter = i; } } maxLength; string palindrome = ""; for (int i=maxCenter-maxLength+1; i<maxCenter+maxLength; i++) { if (str[i] != '#') palindrome += str[i]; } return palindrome; } };
相关文章推荐
- [LeetCode] Longest Palindromic Substring
- LeetCode - Longest Palindromic Substring
- Leetcode-Longest Palindromic Substring
- Leetcode 5. Longest Palindromic Substring(java版)
- LeetCode:Longest Palindromic Substring
- LeetCode之Longest Palindromic Substring
- leetcode:5. Longest Palindromic Substring
- LeetCode *** 5. Longest Palindromic Substring
- leetcode - Longest Palindromic Substring
- LeetCode:Longest Palindromic Substring
- leetCode Longest Palindromic Substring
- LeetCode:Longest Palindromic Substring
- leetcode 5.Longest Palindromic Substring
- LeetCode题目: 5.Longest Palindromic Substring
- Leetcode: Longest Palindromic Substring
- 【Leetcode】Longest Palindromic Substring
- Leetcode日记(4)---Longest Palindromic Substring
- LeetCode题库解答与分析——#5.最长回文子串LongestPalindromicSubstring
- LeetCode - Longest Palindromic Substring
- [LeetCode]Longest Palindromic Substring