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