Java easy to read solution


  • 0
    M

    Start from "1" and make string again and again.

    class Solution {
        public String countAndSay(int n) {
            String say = "1";
            for (int i = 1; i < n; i++) {
                say = process(say);
            }
            return say;
        }
        
        public String process(String before) {
            StringBuilder after = new StringBuilder();
            
            int i = 0;
            while (i < before.length()) {
                int j = i;
                // To count same numbers
                while (j < before.length() && before.charAt(i) == before.charAt(j)) j++;
                
                // Add count
                after.append(j-i);
                // Add number 
                after.append(before.charAt(i));
                i = j;
            }
            
            return after.toString();
        }
    }
    

Log in to reply
 

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