"Leetcode" solution in Java--easy2

Source: Internet
Author: User

Reprint please specify the original address: http://www.cnblogs.com/ygj0930/p/6410409.html

6:reverse String

Write a function that takes a string as input and returns the string reversed.

This topic: string reversal questions.

Idea: This problem in the first Class C + + time on the machine problem has been done, then the idea is: to convert a string to char[], from the end of the head to traverse a reverse order to copy the character to another array (from start to finish), and then the new array ToString (). Now in Java, replace the new array with StringBuffer, reverse-traverse char[] One by one append to buffer, then ToString (). Because each element is traversed once, the complexity O (n).

 Public string reversestring (string s) {        char[] chars=S.tochararray ();        StringBuffer buffer=new  stringbuffer ();                for (int i=chars.length-1;i>=0;--i) {            buffer.append (chars[i]);        }                 return buffer.tostring ();    }

The second way of thinking is: to char[the front and back half of the exchange can, just traverse half, the complexity of O (N/2).

  Publicstring reversestring (string s) {Char[] chars=S.tochararray (); intHalf=chars.length/2;  for(inti=0;ii) {            CharTemp=chars[chars.length-1-i]; Chars[chars.length-1-i]=Chars[i]; Chars[i]=temp; }         //note here: char[] Conversion to string is implemented through new string (char[]).        return NewString (chars); }

"Leetcode" solution in Java--easy2

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.