码迷,mamicode.com
首页 > 其他好文 > 详细

CTCI 1.2

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

标签:style   blog   java   color   os   art   

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

标签:style   blog   java   color   os   art   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!