Simple Java solution


  • 1
    V
    public String countAndSay(int n) {
        int count = 1;
        String s = "1";
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i < n ; i++){
            sb.setLength(0);
            count = 1;
            for(int j = 1; j < s.length(); j++){
                if(s.charAt(j) != s.charAt(j-1)){
                    sb.append(count);
                    sb.append(s.charAt(j-1));
                    count = 0;
                }
                count++;
            }
            if(count > 0){
                sb.append(count);
                sb.append(s.charAt(s.length()-1));
            }
            s = sb.toString();
        }
        return s;
    }

Log in to reply
 

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