Reverse String–LeetCode#344

344.Reverse String

Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
思路:字符串反转输出。转换成char[]遍历逆序后转回String输出
代码如下:

/**
 * Created by Poldi on 2017/7/7.
 */
public class ReverseString {
    public String reverseString(String s) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length/2; i++) {
            char temp = chars[i];
            chars[i] = chars[chars.length-1-i];
            chars[chars.length-1-i] = temp;
        }
        return String.valueOf(chars);
    }
    public static void main(String[] args) {
        ReverseString reverseString = new ReverseString();
        System.out.println(reverseString.reverseString("hello"));
    }
}

也可以利用StringBuilder的reverse()直接逆序
代码如下:

public String reverseString(String s) {
    StringBuilder sb = new StringBuilder(s);
    return sb.reverse().toString();
}
文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部