首页 > 代码库 > CTCI 1.2

CTCI 1.2

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(""));    }}