-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
45 lines (40 loc) · 1.03 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <algorithm>
#include <climits>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
private:
pair<int, int> expandCentre(const string& s, int left, int right) {
while (left >= 0 && right < s.length() && s[left] == s[right]) {
--left;
++right;
}
// Move left/right indices back to compensate for last iteration
return {left + 1, right - 1};
}
public:
string longestPalindrome(string s) {
int n = s.length();
int start = 0;
int maxLength = 1;
for (int i = 0; i < n; ++i) {
const auto& [oddL, oddR] = expandCentre(s, i, i);
const auto& [evenL, evenR] = expandCentre(s, i, i + 1);
if (oddR - oddL + 1 > maxLength) {
start = oddL;
maxLength = oddR - oddL + 1;
}
if (evenR - evenL + 1 > maxLength) {
start = evenL;
maxLength = evenR - evenL + 1;
}
}
return s.substr(start, maxLength);
}
};