My Java Solution


  • 0
    public String countAndSay(int n) {
        if(n < 1) return null;
        else if(n==1) return "1";
        else if(n==2) return "11";
        return countAndSayHelper(n-1, 0, "1");
    }
    
    public String countAndSayHelper(int n, int index, String str) {
        if(index == n) return str;
        
        StringBuilder sb = new StringBuilder();
        int slow=0, fast=0, prev=Character.getNumericValue(str.charAt(0)), cur, count=1;
        for(int i=1; i<str.length(); i++) {
            cur = Character.getNumericValue(str.charAt(i));
            if(prev == cur) {
                count++;
            } else {
                sb.append(Integer.toString(count) + Integer.toString(prev));
                count = 1;
                prev = cur;
            }
        }
        sb.append(Integer.toString(count) + Integer.toString(prev));
        return countAndSayHelper(n, index+1, sb.toString());
    }

Log in to reply
 

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