My Recursive Java Solution


  • 0
    T
    public String countAndSay(int n) {
        return countAndSayHelper("1", n);
    }
    
    private String countAndSayHelper(String seq, int n) {
        if (n == 0 || n == 1) {
            return seq;
        }
        
        StringBuilder sb = new StringBuilder();
        int i = 0;
        int len = seq.length();
        
        while (i < len) {
            char curr = seq.charAt(i);
            int count = 1;
    
            while (i < len - 1 && curr == seq.charAt(i + 1)) {
                // count appearance of the number
                count++;
                i++;
            }
            
            sb.append(count);
            sb.append(curr);
            i++;
        }
        
        return countAndSayHelper(sb.toString(), n - 1);   
    }

Log in to reply
 

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