Skip to content

Commit 52dd566

Browse files
author
Li Li
committed
add code of 5
1 parent 37b2c6a commit 52dd566

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
for each point, try to expand to palindrom, and compare with maxLen.
3+
*/
4+
public class Solution {
5+
private int start, maxLen;
6+
public string LongestPalindrome(string s) {
7+
int len = s.Length;
8+
if (len < 2) return s;
9+
for (int i = 0; i < s.Length - 1; i++) {
10+
//assume odd length, try to extend Palindrome as possible
11+
ExpandAroundCenter(s, i, i);
12+
//assume even length.
13+
ExpandAroundCenter(s, i, i + 1);
14+
}
15+
return s.Substring(start, maxLen);
16+
}
17+
private void ExpandAroundCenter(string s, int left, int right) {
18+
while ( left >= 0 && right < s.Length && s[left] == s[right]) {
19+
left--;
20+
right++;
21+
}
22+
if (maxLen < right - left - 1) {
23+
start = left + 1;
24+
maxLen = right - left - 1;
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)