Skip to content

Commit 3b35cc1

Browse files
authored
Add longest palindromic substring (TheAlgorithms#2379)
1 parent 6023b45 commit 3b35cc1

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Longest Palindromic Substring
2+
import java.util.Scanner;;
3+
4+
5+
class LongestPalindromicSubstring {
6+
public static void main(String[] args) {
7+
Solution s = new Solution();
8+
String str = "";
9+
Scanner sc = new Scanner(System.in);
10+
System.out.print("Enter the string: ");
11+
str = sc.nextLine();
12+
System.out.println("Longest substring is : "+s.longestPalindrome(str));
13+
}
14+
}
15+
16+
class Solution {
17+
public String longestPalindrome(String s) {
18+
if (s == null || s.length() == 0) {
19+
return "";
20+
}
21+
int n = s.length();
22+
String maxStr = "";
23+
for (int i = 0; i < n; ++i) {
24+
for (int j = i; j < n; ++j) {
25+
if (isValid(s, i, j) == true) {
26+
if (j - i + 1 > maxStr.length()) { // update maxStr
27+
maxStr = s.substring(i, j + 1);
28+
}
29+
}
30+
}
31+
}
32+
return maxStr;
33+
}
34+
35+
private boolean isValid(String s, int lo, int hi) {
36+
int n = hi - lo + 1;
37+
for (int i = 0; i < n / 2; ++i) {
38+
if (s.charAt(lo + i) != s.charAt(hi - i)) {
39+
return false;
40+
}
41+
}
42+
return true;
43+
}
44+
}

0 commit comments

Comments
 (0)