-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathprog13.java
72 lines (51 loc) · 1.75 KB
/
prog13.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//13. program to find the longest Palindrome Substring within a string
package chap3;
import java.util.Scanner;
public class prog13
{
static void printSubStr(String str, int low, int high)
{
System.out.println(str.substring(low, high + 1));
}
static int longestPalSubstr(String str) {
int n = str.length();
boolean table[][] = new boolean[n][n];
int maxLength = 1;
for (int i = 0; i < n; ++i)
table[i][i] = true;
int start = 0;
for (int i = 0; i < n - 1; ++i) {
if (str.charAt(i) == str.charAt(i + 1)) {
table[i][i + 1] = true;
start = i;
maxLength = 2;
}
}
for (int k = 3; k <= n; ++k)
{
for (int i = 0; i < n - k + 1; ++i)
{
int j = i + k - 1;
if (table[i + 1][j - 1] && str.charAt(i) ==
str.charAt(j)) {
table[i][j] = true;
if (k > maxLength) {
start = i;
maxLength = k;
}
}
}
}
System.out.print("Longest palindrome substring is; ");
printSubStr(str, start, start + maxLength - 1);
return maxLength;
}
public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
String str ;
System.out.println("Enter a String");
str =sc.nextLine();
System.out.println("Length is: " + longestPalSubstr(str));
}
}