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.
Solution:
class Solution {
public:
string longestPalindrome(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string max_string , ans_string;
int size = s.size();
if (size < 2)
return s;
for (int i = 0; i < size - 1; i++) {
if (s[i] == s[i+1]) {
ans_string = palindrom(s, i, i+1);
if (ans_string.size() > max_string.size())
max_string = ans_string;
}
if (i != size - 1 && s[i] == s[i+2]) {
ans_string = palindrom(s, i, i+2);
if (ans_string.size() > max_string.size())
max_string = ans_string;
}
}
return max_string;
}
string palindrom(string s, int i, int j) {
string ret_string;
int size = s.size();
while (i >= 0 && j < size && s[i] == s[j]) {
i--;
j++;
}
for (int iter = i + 1; iter < j; iter++) {
ret_string += s[iter];
}
return ret_string;
}
};
========= Another attempt ======
class Solution {
public:
string longestPalindrome(string s) {
string ans;
if (s.size() < 2) {
return s;
}
for (int i = 0; i < s.size(); i++) {
// odd length.
int left = i;
int right = i;
while (left >= 0 && right < s.size()) {
if (s[left] != s[right]) {
break;
}
left--;
right++;
}
left++;
right--;
// length check.
if (right - left + 1 > ans.size()) {
ans = s.substr(left, right - left + 1);
}
// even length.
left = i;
right = i + 1;
while (left >= 0 && right < s.size()) {
if (s[left] != s[right]) {
break;
}
left--;
right++;
}
left++;
right--;
// length check.
if (right - left + 1 > ans.size()) {
ans = s.substr(left, right - left + 1);
}
}
return ans;
}
};
No comments:
Post a Comment