Mercurial > repos > rliterman > csp2
comparison CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/opt/bbmap-39.01-1/current/fun/Palindrome.java @ 68:5028fdace37b
planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author | jpayne |
---|---|
date | Tue, 18 Mar 2025 16:23:26 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
67:0e9998148a16 | 68:5028fdace37b |
---|---|
1 package fun; | |
2 | |
3 import shared.Tools; | |
4 | |
5 public class Palindrome { | |
6 | |
7 public static void main(String[] args){ | |
8 System.out.println(longestPalindrome(args[0])); | |
9 } | |
10 | |
11 public static String longestPalindrome(String s){ | |
12 int longestLength=0; | |
13 int longestStart=0; | |
14 for(int i=0; i<s.length(); i++){ | |
15 int lenEven=palindromeLength(s, i, i+1); | |
16 if(lenEven>longestLength){ | |
17 longestLength=lenEven; | |
18 longestStart=i-lenEven/2+1; | |
19 } | |
20 int lenOdd=palindromeLength(s, i, i); | |
21 if(lenOdd>longestLength){ | |
22 longestLength=lenOdd; | |
23 longestStart=i-lenOdd/2; | |
24 } | |
25 } | |
26 return s.substring(longestStart, longestStart+longestLength+1); | |
27 } | |
28 | |
29 public static int palindromeLengthOdd(String s, int middle){ | |
30 int length=1; | |
31 int a=middle-1, b=middle+1; | |
32 while(a>=0 && b<s.length()){ | |
33 if(s.charAt(a)==s.charAt(b)){ | |
34 a--; | |
35 b++; | |
36 length+=2; | |
37 }else{ | |
38 break; | |
39 } | |
40 } | |
41 return length; | |
42 } | |
43 | |
44 public static int palindromeLengthEven(String s, int middle){ | |
45 int length=0; | |
46 int a=middle, b=middle+1; | |
47 while(a>=0 && b<s.length()){ | |
48 if(s.charAt(a)==s.charAt(b)){ | |
49 a--; | |
50 b++; | |
51 length+=2; | |
52 }else{ | |
53 break; | |
54 } | |
55 } | |
56 return length; | |
57 } | |
58 | |
59 public static int palindromeLength(String s, int a, int b){ | |
60 while(a>=0 && b<s.length()){ | |
61 if(s.charAt(a)!=s.charAt(b)){break;} | |
62 a--; | |
63 b++; | |
64 } | |
65 return Tools.max(0, b-a-2); | |
66 } | |
67 | |
68 public static boolean isPalindrome(String s, int a, int b){ | |
69 while(a<b){ | |
70 if(s.charAt(a)!=s.charAt(b)){ | |
71 return false; | |
72 } | |
73 } | |
74 return true; | |
75 } | |
76 | |
77 } |