Packagestring.string1_5; Public classpalindrome{/*** Move from both ends to the middle *@paramSTR *@return */ Public Static Booleanispalindrome (String str) {if(str = =NULL|| Str.equals ("")) return false ; intleft = 0 ; intright = Str.length ()-1 ; while(Left <Right ) { if(Str.charat (left++)! = Str.charat (right--)) return false ; } return true ; } /*** Move from center to both ends *@paramSTR *@return */ Public Static BooleanisPalindrome2 (String str) {if(str = =NULL|| Str.equals ("")) return false ; intleft = Str.length ()/2 ; intright = Str.length ()-1-Left ; while(Left >= 0) { if(Str.charat (left--)! = Str.charat (right++)) return false ; } return true ; } /*** Determine if the linked list is a palindrome *@paramnode *@return */ Public Static BooleanIsPalindrome3 (ListNode node) {//when the list is empty or the list contains only one element if(node = =NULL|| Node.next = =NULL) return true ; ListNode Head=NewListNode (); Head.next=node; ListNode Slow=Head; ListNode Quick=Head; while(Quick.next! =NULL) {Slow=Slow.next; for(inti=0; i<2; i++) if(Quick.next! =NULL) Quick=Quick.next; Else Break ; } ListNode F=Slow.next; Slow.next=NULL ; ListNode l=NULL ; ListNode T=NULL ; while(F! =NULL) {T=F; F=F.next; T.next=l; L=T; } Slow.next=T; Quick=Slow.next; Slow=node; while(Quick! =NULL) { if(slow.ch! =quick.ch)return false ; Slow=Slow.next; Quick=Quick.next; } return true ; } Public Static voidMain (string[] args) {/*ListNode Node1 = new ListNode (' a '); ListNode node2 = new ListNode (' B '); ListNode node3 = new ListNode (' C '); ListNode node4 = new ListNode (' C '); ListNode node5 = new ListNode (' B '); ListNode node6 = new ListNode (' a '); Node1.next = Node2; Node2.next = Node3; Node3.next = Node4; Node4.next = NODE5; Node5.next = Node6;*/ListNode Node1=NewListNode (' a ') ; ListNode Node2=NewListNode (' B ') ; ListNode Node3=NewListNode (' C ') ; ListNode Node5=NewListNode (' a ') ; ListNode Node6=NewListNode (' a ') ; Node1.next=Node2; Node2.next=Node3; Node3.next=Node5; Node5.next=Node6; System.out.println (IsPalindrome3 (Node1)); }}classlistnode{Charch; ListNode Next; PublicListNode () {} PublicListNode (Charch) { This. ch =ch; }}
Java palindrome string