LeetCode 344 Reverse String

来源:互联网 发布:matlab数组分号 编辑:程序博客网 时间:2024/05/16 02:16

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

Example:
Given s = "hello", return "olleh".

思路1: 转为StringBuffer,用StringBuffer里面的reverse函数转换

public class Solution {
    public String reverseString(String s) {
        StringBuffer sb = new StringBuffer (s);
        return sb.reverse().toString();
}

思路2: 转为char数组,倒序输出到String

public class Solution {
    public String reverseString(String s) {
        String result = "";
        for (int i=s.length()-1; i>=0; i--){ 
             result += String.valueOf(s.charAt(i));; 
        }
        return result;

}

1 0
原创粉丝点击