Leetcode 344 Reverse String

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

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

思路:比较容易从代码看明白。注意下StringBuffer这个类的使用,在涉及到字符串的增删改查时可以使用,比String方便多了

public class S344 {
    public String reverseString(String s) {
        //LTE
        /*
        String ret = "";
        for (int i = 0;i < s.length();i++) {
            ret += s.charAt(s.length()-1-i);
        }
        return ret;*/
        /*最简洁
        StringBuffer b = new StringBuffer(s);
        return b.reverse().toString();
        */
        //最快的 
        char[] retc = new char[s.length()];
        char[] sc = s.toCharArray();
        int i = 0,j = s.length()-1;
        while (i <= j) { //注意不能是 i!=j
            retc[j] = sc[i];
            retc[i] = sc[j];
            i++;
            j--;
        }
        return new String(retc);
    }
}
原文地址:https://www.cnblogs.com/fisherinbox/p/5439643.html