LeetCode-344. Reverse String-Java

来源:互联网 发布:催眠是真的吗 知乎 编辑:程序博客网 时间:2024/06/07 07:53

一. 题目
Write a function that takes a string as input and returns the string reversed.
Example: Given s = “hello”, return “olleh”

二. 思路
题目为翻转一个字符串,原则上来说可以用StringBuffer的reverse(),也可以把字符串转换成字符数组,前后两两交换,再转换成字符串。

三. AC代码

方法1. 交换前后字符

public String reverseString(String s) {        char[] reverse=s.toCharArray();        char temp;        int count=reverse.length/2;        for(int i=0;i<count;i++){            temp=reverse[i];            reverse[i]=reverse[reverse.length-1-i];            reverse[reverse.length-1-i]=temp;        }        return new String(reverse);    }

方法2. 字符串翻转

public static String reverseString(String s) {    StringBuffer buffer = new StringBuffer(s.length());     for (int i =0; i<s.length(); i++) {        buffer.append(s.charAt(s.length()-1-i));     }    return buffer.toString(); }或public static String reverseString(String s) {    StringBuffer buffer = new StringBuffer(s);     return buffer.reverse().toString(); }
0 0
原创粉丝点击