Java Pen Questions

Source: Internet
Author: User

1. Implement string inversion

Provides seven scenarios for string inversion

ImportJava.util.Stack; Public classStringreverse { Public Staticstring Reverse1 (string s) {intLength =s.length (); if(Length <= 1)   returns; String Left= s.substring (0, LENGTH/2); String Right= S.substring (LENGTH/2, length); returnReverse1 (right) +Reverse1 (left);}  Public Staticstring Reverse2 (string s) {intLength =s.length (); String Reverse= "";  for(inti = 0; i < length; i++) Reverse= S.charat (i) +reverse; returnreverse;}  Public Staticstring Reverse3 (string s) {Char[] Array =S.tochararray (); String Reverse= "";  for(inti = array.length-1; I >= 0; i--) Reverse+=Array[i]; returnreverse;}  Public Staticstring Reverse4 (string s) {return NewStringBuffer (s). Reverse (). toString ();  Public Staticstring Reverse5 (String orig) {Char[] s =Orig.tochararray (); intn = s.length-1; intHalflength = N/2;  for(inti = 0; I <= halflength; i++) {   Chartemp =S[i]; S[i]= S[n-i]; S[n-I] =temp; }  return NewString (s);}  Public Staticstring Reverse6 (string s) {Char[] str =S.tochararray (); intBegin = 0; intEnd = S.length ()-1;  while(Begin <end) {Str[begin]= (Char) (Str[begin] ^Str[end]); Str[end]= (Char) (Str[begin] ^Str[end]); Str[begin]= (Char) (Str[end] ^Str[begin]); Begin++; End--; }    return NewString (str);}  Public Staticstring Reverse7 (string s) {Char[] str =S.tochararray (); Stack<Character> stack =NewStack<character>();  for(inti = 0; i < str.length; i++) Stack.push (Str[i]); String Reversed= "";  for(inti = 0; i < str.length; i++) Reversed+=Stack.pop (); returnreversed;} }

Java Pen Questions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.