来源:Leetcode
原帖:http://oj.leetcode.com/problems/longest-palindromic-substring/
题目:
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.
代码:
原帖:http://oj.leetcode.com/problems/longest-palindromic-substring/
题目:
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.
代码:
class Solution {
public:
string longestPalindrome(string s) {
int N = s.length();
int start = 0, maxlen = 0;
for (int center = 0; center < N; center++) {
expand(s, center, center, maxlen, start);
expand(s, center, center + 1, maxlen, start);
}
return s.substr(start, maxlen);
}
void expand(const string& s, int left, int right, int& maxlen, int& start){
while (left >= 0 && right < s.length() && s[left] == s[right]) {
left--;
right++;
}
if (right - left - 1 > maxlen) {
maxlen = right - left - 1;
start = left + 1;
}
}
};
No comments:
Post a Comment