Leetcode 5. Longest Palindromic Substring
Given a string s
, return the longest palindromic substring in s
.
What is a palindrome?
A palindrome is a string that reads the same forward and backward.
s
non-empty?1000
characters.n
is the length of the string.#include <string>
using namespace std;
class Solution {
public:
string longestPalindrome(string s) {
if (s.empty()) return "";
int start = 0, maxLength = 1;
for (int i = 0; i < s.length(); ++i) {
// Odd length palindromes
expandAroundCenter(s, i, i, start, maxLength);
// Even length palindromes
expandAroundCenter(s, i, i + 1, start, maxLength);
}
return s.substr(start, maxLength);
}
private:
void expandAroundCenter(const string& s, int L, int R, int& start, int& maxLength) {
while (L >= 0 && R < s.length() && s[L] == s[R]) {
--L;
++R;
}
int len = R - L - 1; // Length of the currently found palindrome
if (len > maxLength) {
start = L + 1;
maxLength = len;
}
}
};
This code defines a class Solution
that contains a method longestPalindrome
to find the longest palindromic substring. The helper method expandAroundCenter
is used to expand around potential centers and update the longest palindrome found during the process.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?