码迷,mamicode.com
首页 > 其他好文 > 详细

344. Reverse String

时间:2018-12-20 01:05:50      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:font   The   com   use   sed   bsp   methods   NPU   nap   

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;

 

 

344. Reverse String

标签:font   The   com   use   sed   bsp   methods   NPU   nap   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10147078.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!