Skip to content

Commit 894c150

Browse files
authored
Add Longest Palindromic Substring in Java (#5184)
1 parent ef40849 commit 894c150

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
public class LongestPalindromicSubstring {
2+
3+
private static final String usage_msg = "Usage: please provide a string that contains at least one palindrome\n";
4+
5+
private static int expandAroundCenter(String s, int left, int right) {
6+
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
7+
left--;
8+
right++;
9+
}
10+
return right - left - 1;
11+
}
12+
13+
private static boolean longestPalindromicSubstring(String s, StringBuilder result) {
14+
if (s == null || s.isEmpty()) {
15+
result.setLength(0);
16+
return false;
17+
}
18+
19+
int start = 0, maxLength = 0;
20+
int len = s.length();
21+
22+
for (int i = 0; i < len; i++) {
23+
int len1 = expandAroundCenter(s, i, i);
24+
int len2 = expandAroundCenter(s, i, i + 1);
25+
int currLen = Math.max(len1, len2);
26+
27+
if (currLen > maxLength) {
28+
start = i - (currLen - 1) / 2;
29+
maxLength = currLen;
30+
}
31+
}
32+
33+
if (maxLength > 1) {
34+
result.setLength(0);
35+
result.append(s.substring(start, start + maxLength));
36+
return true;
37+
}
38+
39+
result.setLength(0);
40+
return false;
41+
}
42+
43+
public static void main(String[] args) {
44+
if (args.length != 1) {
45+
System.out.print(usage_msg);
46+
System.exit(1);
47+
}
48+
49+
String input = args[0];
50+
StringBuilder result = new StringBuilder();
51+
52+
if (longestPalindromicSubstring(input, result) && result.length() > 0) {
53+
System.out.println(result);
54+
} else {
55+
System.out.print(usage_msg);
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)