344. Reverse String

原题链接:https://leetcode.com/problems/reverse-string/description/
实现如下:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.reverseString("hello"));
    }

    /**
     * 方法二:使用双指针
     *
     * @param s
     * @return
     */
    public String reverseString(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        char[] chars = s.toCharArray();
        int i = 0, j = chars.length - 1;
        while (i < j) {
            char temp = chars[i];
            chars[i] = chars[j];
            chars[j] = temp;

            i++;
            j--;
        }
        return new String(chars);
    }

    /**
     * 方法一:使用递归,字符串过长时会导致栈溢出
     *
     * Runtime Error Message: Exception in thread "main" java.lang.StackOverflowError
     * @param s
     * @return
     */
    public String reverseString1(String s) {
        if (s == null || s.length() < 2) {
            return s;
        }
        return s.substring(s.length() - 1, s.length()) + reverseString(s.substring(0, s.length() - 1));
    }

}

参考

http://www.cnblogs.com/optor/p/8758816.html

原文地址:https://www.cnblogs.com/optor/p/8758766.html