Easy to understand Java solution, beats 98%


  • 0
    M
    public class Solution {
        public String countAndSay(int n) {
            if(n==1) return "1";
            char[] chars = countAndSay(n-1).toCharArray();
            StringBuilder sb = new StringBuilder();
            int count=0;
            int i=0;
            for(;i<chars.length;i++){
                if(i==0 || chars[i]==chars[i-1]) count++;
                else{
                    sb.append(count);
                    sb.append(chars[i-1]);
                    count=1;
                }
            }
            
            sb.append(count);
            sb.append(chars[i-1]);
            return sb.toString();
        }
    }

Log in to reply
 

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