Java iterative solution


  • 0
    L
        public String countAndSay(int n) {
            String s = "1";
            StringBuilder builder = new StringBuilder(s);
            for(int idx=2;idx<=n;idx++) {
                builder.setLength(0);
                int count=1;
                for(int i=0;i<=s.length()-1;i++) {
                    if(i==s.length()-1 || s.charAt(i)!=s.charAt(i+1)) {
                        builder.append(count);
                        builder.append(s.charAt(i));
                        count=1;
                    }
                    else {
                        count++;
                    }
                }
                s=builder.toString();
            }
            
            return s;
        }
    

Log in to reply
 

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