Skip to content

Commit cce978b

Browse files
authored
longest palindrome substring
1 parent 233742d commit cce978b

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

longestPalindromeSubstr.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
private:
3+
int expandString(const string &s, int left, int right){
4+
while(left>=0 && right<s.size() && s[left] == s[right]){
5+
left--;
6+
right++;
7+
}
8+
return right - left - 1;
9+
}
10+
11+
public:
12+
string longestPalindrome(string s) {
13+
int n = s.size();
14+
int maxlen = 0;
15+
int start = 0;
16+
17+
for(int i = 0; i<n; i++){
18+
int l1 = expandString(s,i,i);
19+
int l2 = expandString(s,i,i+1);
20+
int l = max(l1,l2);
21+
22+
if(l > maxlen){
23+
maxlen = l;
24+
start = i - (l-1)/2;
25+
}
26+
}
27+
return s.substr(start, maxlen);
28+
}
29+
};

0 commit comments

Comments
 (0)