Skip to content

Commit ac04284

Browse files
author
Li Li
committed
add dp solution to 5
1 parent 930f364 commit ac04284

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

top-interview-questions/5. Longest Palindromic Substring.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,37 @@ private void ExpandAroundCenter(string s, int left, int right) {
2424
maxLen = right - left - 1;
2525
}
2626
}
27+
}
28+
29+
// Dynamic Programming
30+
/*
31+
consider whether using this new character as end could produce new palindrome
32+
string of length (current length +1) or (current length +2), no more than length + 3;
33+
*/
34+
public class Solution {
35+
public String LongestPalindrome(String s) {
36+
int maxLen = 0;
37+
int start = -1;
38+
for (int i = 0; i < s.Length; i++) {
39+
if (IsPalindrome(s, i - maxLen - 1, i)) {
40+
start = i - maxLen - 1;
41+
maxLen += 2;
42+
} else if (IsPalindrome(s, i - maxLen, i)) {
43+
start = i - maxLen;
44+
maxLen += 1;
45+
}
46+
}
47+
return s.Substring(start, maxLen);
48+
}
49+
private bool IsPalindrome(string s, int start, int end) {
50+
if (start < 0) {
51+
return false;
52+
}
53+
while (start < end) {
54+
if (s[start++] != s[end--]) {
55+
return false;
56+
}
57+
}
58+
return true;
59+
}
2760
}

0 commit comments

Comments
 (0)