Sharing my easy-to-understand and short java solution


  • 0
    C
    public String countAndSay(int n) {
        if(n < 1) return "";
        String str = "1", result = new String();
        result = generateNext(str, n);
        return result;
    }
    private String generateNext(String s, int n) {
        if(n == 1) return s;
        int len = s.length();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < len; i++) {
            int j = i;
            while(i + 1 < len && s.charAt(i) == s.charAt(i + 1)) i++;
            sb.append(i - j + 1);
            sb.append(s.charAt(i));
        }
        return generateNext(sb.toString(), n - 1);
    }

Log in to reply
 

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