-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestPalidrome.java
More file actions
47 lines (42 loc) · 1.76 KB
/
LongestPalidrome.java
File metadata and controls
47 lines (42 loc) · 1.76 KB
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
package additional_question;
public class LongestPalidrome {
private static int lowPos;
private static int maxLength;
public static void main(String[] args){
System.out.println(longestPalidrom("civilwartestingwhetherthatnaptionoranynarti"
+ "onsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefie"
+ "mldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplacefo"
+ "rthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproper"
+ "thatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannoth"
+ "allowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfarabov"
+ "eourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayhe"
+ "rebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretot"
+ "heulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforust"
+ "obeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwet"
+ "akeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionth"
+ "atweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsd"
+ "erGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeo"
+ "pleshallnotperishfromtheearth"));
}
public static String longestPalidrom(String s){
if(s.length()<2){
return s;
}
for(int i=0; i<s.length()-1; i++){
extendPalidrom(s, i, i);
extendPalidrom(s, i, i+1);
}
System.out.println("");
return s.substring(lowPos, lowPos+maxLength);
}
public static void extendPalidrom(String s, int m, int n){
while(m>=0&&n<s.length()&&s.charAt(m)==s.charAt(n)){
m--;
n++;
}
if(maxLength<n-m-1){
lowPos = m+1;
maxLength = n-m-1;
}
}
}