344. Reverse String

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于344. Reverse String的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 344 - Reverse String

344. Reverse String

LeetCode(344) Reverse String

344. (Reverse String)反转字符串

LeetCode: 344 Reverse String

LeetCode解题思路:344. Reverse String