Concise Java solution


  • 0
    S

    Start with 1 and say the number n - 1 times.

    public String countAndSay(int n) {
        String s = "1";
        for (int i = 1; i < n; i++) {
            s = say(s);
        }
        return s;
    }
    
    private String say(String n) {
        int i = 0;
        StringBuilder sb = new StringBuilder();
        while (i < n.length()) {
            int count = 0;
            while (i < n.length() - 1 && n.charAt(i) == n.charAt(i + 1)) {
                i++;
                count++;
            }
            sb.append(count + 1).append(n.charAt(i++));
        }
        return sb.toString();
    }
    

Log in to reply
 

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