Skip to content

Commit ef8c12e

Browse files
authored
Adding solution to LongestPallindromicSubstring (#106)
* Added Regular Expression matching * Revert "Added Regular Expression matching" This reverts commit 4449207. * adding solution of daily probs
1 parent 32450ba commit ef8c12e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
public class LongestPallindromicSubstring {
2+
3+
public String longestPalindrome(String s) {
4+
if (s == null || s.length() < 1) return "";
5+
int start = 0;
6+
int end = 0;
7+
8+
for (int i = 0; i < s.length(); i++) {
9+
int len1 = expandFromMiddle(s, i, i); // racecar
10+
int len2 = expandFromMiddle(s, i, i + 1); // abba
11+
int len = Math.max(len1, len2);
12+
if (len > end - start) {
13+
start = i - ((len - 1) / 2);
14+
end = i + (len / 2);
15+
}
16+
}
17+
return s.substring(start, end + 1);
18+
}
19+
20+
// racecar
21+
// 0123456
22+
// i = 3
23+
// len1 = 7
24+
// start = 3 - (7-1/2) = 0
25+
// end = 3 + 7/2 = 3 + 3 = 6
26+
27+
public int expandFromMiddle(String s, int left, int right) {
28+
if (s == null || left > right)
29+
return 0;
30+
31+
while (left >= 0 && right < s.length() &&
32+
s.charAt(left) == s.charAt(right)) {
33+
left--;
34+
right++;
35+
}
36+
return right - left - 1; // -1 for that extra right++ increment in while loop
37+
}
38+
}
39+

0 commit comments

Comments
 (0)