Simple Java Solution Using Two Pointers


  • 0
    public String countAndSay(int n) {
        StringBuilder prev = new StringBuilder("1");
        StringBuilder curr = new StringBuilder("");
        int i = 0;
        while (--n > 0) {
            for (int j = 1; j <= prev.length(); j++) {
                if (j == prev.length() || prev.charAt(j) != prev.charAt(i)) {
                    curr.append(j-i);
                    curr.append(prev.charAt(i));
                    i = j;
                }
            }
            prev = curr; i = 0;
            curr = new StringBuilder("");
        }
        return prev.toString();
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.