leetcode:344. Reverse String

Source: Internet
Author: User

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

Example:
Given s = "Hello", Return "Olleh".

The main idea is to give a string, get the reverse string

Corner case: empty string or string length of 0

Solution One:

Request extra space, index points to the end of the original string, and constructs a new string in reverse sequence

 Public classSolution { Publicstring reversestring (string s) {if(s = =NULL|| S.length () = = 0)        {            returns; } String Res= ""; intindex = S.length ()-1;  for(; index >= 0; index--) {res+=S.charat (index); }                returnRes; }}

Complexity of Time: N, Spatial complexity: N
Timeout

Solution Two:

Double pointer point to tail, directly swap characters. No extra space required, only loop N/2 times

 Public classSolution { Publicstring reversestring (string s) {if(s = =NULL|| S.length () = = 0)        {            returns; }                intleft = 0; intright = S.length ()-1; Char[] Schar =S.tochararray ();  while(Left <Right ) {            Chartemp =Schar[left]; Schar[left]=Schar[right]; Schar[right]=temp; Left++; Right--; }                return NewString (Schar); }}

leetcode:344. Reverse String

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.