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