Java solution, two pointers


  • 0
    N
    public String countAndSay(int n) {
        StringBuilder sb = new StringBuilder();
        sb.append(1);
        for (int i = 1; i < n; i++) {
            sb = count(sb);
        }
        return sb.toString();
    }
    
    private StringBuilder count(StringBuilder pre) {
        int start = 0, end = 0;
        StringBuilder sb = new StringBuilder();
        while (end < pre.length()) {
            while (end < pre.length() && pre.charAt(start) == pre.charAt(end)) {
                end++;
            }
            sb.append(end - start);
            sb.append(pre.charAt(start));
            start = end;
        }
        return sb;
    }

Log in to reply
 

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