首页 > 其他 > 详细

344. Reverse String

时间:2018-04-09 12:23:05      阅读:188      评论:0      收藏:0      [点我收藏+]

原题链接: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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!