An easy to read Java solution


  • 0
    W

    When the digit is the same, increment the counter. When different, append the frequency and the digit to the StringBuilder. Update the digit to be compared and reset the counter. Repeat the process for n iterations.

    public class Solution {
        public String countAndSay(int n) {
            return countAndSay("1", n-1);
        }
        
        private String countAndSay(String str, int itr) {
            if (itr == 0) {
                return str;
            }
            
            StringBuilder builder = new StringBuilder();
            int count = 0;
            char c = str.charAt(0);
            
            for (int i = 0; i < str.length(); i++) {
                char cur = str.charAt(i);
                if (cur == c) {
                    count++;
                } else {
                    builder.append(count + "" + c);
                    c = cur;
                    count = 1;
                }
            }
            
            builder.append(count + "" + c);
            return countAndSay(builder.toString(), itr-1);
        }
    }
    

Log in to reply
 

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