首页 > 其他 > 详细

CTCI 1.2

时间:2014-07-06 13:33:54      阅读:386      评论:0      收藏:0      [点我收藏+]

Since I mainly use Java, this problem seems meaning less for me to implement it with Java. Just use StringBuilder to append each character in string from the end to the start. The time complexity is O(N) and space complexity is O(N), too. If using C++, two pointers is enough and the space complexity is O(1).

public class ReverseString {
    public String reverseString(String s) {
        StringBuilder sb = new StringBuilder();
        sb.append("");
        for(int i = s.length()-1; i >= 0; i--) {
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        ReverseString rs = new ReverseString();
        System.out.println(rs.reverseString("abcd"));
        System.out.println(rs.reverseString(""));
    }
}

 

CTCI 1.2,布布扣,bubuko.com

CTCI 1.2

原文:http://www.cnblogs.com/pyemma/p/3825828.html

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