annotate 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
rev   line source
jpayne@68 1 package fun;
jpayne@68 2
jpayne@68 3 import shared.Tools;
jpayne@68 4
jpayne@68 5 public class Palindrome {
jpayne@68 6
jpayne@68 7 public static void main(String[] args){
jpayne@68 8 System.out.println(longestPalindrome(args[0]));
jpayne@68 9 }
jpayne@68 10
jpayne@68 11 public static String longestPalindrome(String s){
jpayne@68 12 int longestLength=0;
jpayne@68 13 int longestStart=0;
jpayne@68 14 for(int i=0; i<s.length(); i++){
jpayne@68 15 int lenEven=palindromeLength(s, i, i+1);
jpayne@68 16 if(lenEven>longestLength){
jpayne@68 17 longestLength=lenEven;
jpayne@68 18 longestStart=i-lenEven/2+1;
jpayne@68 19 }
jpayne@68 20 int lenOdd=palindromeLength(s, i, i);
jpayne@68 21 if(lenOdd>longestLength){
jpayne@68 22 longestLength=lenOdd;
jpayne@68 23 longestStart=i-lenOdd/2;
jpayne@68 24 }
jpayne@68 25 }
jpayne@68 26 return s.substring(longestStart, longestStart+longestLength+1);
jpayne@68 27 }
jpayne@68 28
jpayne@68 29 public static int palindromeLengthOdd(String s, int middle){
jpayne@68 30 int length=1;
jpayne@68 31 int a=middle-1, b=middle+1;
jpayne@68 32 while(a>=0 && b<s.length()){
jpayne@68 33 if(s.charAt(a)==s.charAt(b)){
jpayne@68 34 a--;
jpayne@68 35 b++;
jpayne@68 36 length+=2;
jpayne@68 37 }else{
jpayne@68 38 break;
jpayne@68 39 }
jpayne@68 40 }
jpayne@68 41 return length;
jpayne@68 42 }
jpayne@68 43
jpayne@68 44 public static int palindromeLengthEven(String s, int middle){
jpayne@68 45 int length=0;
jpayne@68 46 int a=middle, b=middle+1;
jpayne@68 47 while(a>=0 && b<s.length()){
jpayne@68 48 if(s.charAt(a)==s.charAt(b)){
jpayne@68 49 a--;
jpayne@68 50 b++;
jpayne@68 51 length+=2;
jpayne@68 52 }else{
jpayne@68 53 break;
jpayne@68 54 }
jpayne@68 55 }
jpayne@68 56 return length;
jpayne@68 57 }
jpayne@68 58
jpayne@68 59 public static int palindromeLength(String s, int a, int b){
jpayne@68 60 while(a>=0 && b<s.length()){
jpayne@68 61 if(s.charAt(a)!=s.charAt(b)){break;}
jpayne@68 62 a--;
jpayne@68 63 b++;
jpayne@68 64 }
jpayne@68 65 return Tools.max(0, b-a-2);
jpayne@68 66 }
jpayne@68 67
jpayne@68 68 public static boolean isPalindrome(String s, int a, int b){
jpayne@68 69 while(a<b){
jpayne@68 70 if(s.charAt(a)!=s.charAt(b)){
jpayne@68 71 return false;
jpayne@68 72 }
jpayne@68 73 }
jpayne@68 74 return true;
jpayne@68 75 }
jpayne@68 76
jpayne@68 77 }