344. Reverse String

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

Example 1:

Input: "hello"
Output: "olleh"

Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

The most convenient way is to use StringBuffer class and methods in it.
Solution1:
class Solution {
    public String reverseString(String s) {
        return new StringBuffer(s).reverse().toString();
    }
}  

p.s. This is a website of the difference among String, StringBuffer and StringBuilder.

http://www.cnblogs.com/su-feng/p/6659064.html

Then it's the common solution, which is to convert the string to an array at first, then use a new string to stroe each character in given location.

solution2:

 char[] a = s.toCharArray();
        String res = "";
        for(int i = a.length - 1; i>=0; i--)
            res = res + a[i];
        return res;

 

 
posted @ 2018-12-20 00:16  Schwifty  阅读(112)  评论(0编辑  收藏  举报