Skip to content

Commit 9c3f058

Browse files
committed
Longest Palindromic solution
1 parent 0cc3a5b commit 9c3f058

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
void compare(string s, int left, int right, int& max_start, int& max_end){
4+
while(left >= 0 && right < s.length() && s[left] == s[right]){
5+
left--;
6+
right++;
7+
}
8+
9+
if(max_end - max_start < right - left - 1){
10+
max_start = left + 1;
11+
max_end = right - 1;
12+
}
13+
}
14+
15+
string longestPalindrome(string s) {
16+
int max_start = 0;
17+
int max_end = 0;
18+
19+
for(int i = 0; i < s.length(); i++){
20+
compare(s, i, i, max_start, max_end);
21+
compare(s, i, i + 1, max_start, max_end);
22+
}
23+
24+
return s.substr(max_start, max_end - max_start + 1);
25+
}
26+
};

0 commit comments

Comments
 (0)