Easy to understand Java Solution


  • 0
    A
    public class Solution {
        public String countAndSay(int n) {
            String number = String.valueOf(1);
            
            for (int i=2; i<=n; i++) {
                
                StringBuilder seqBuilder = new StringBuilder();
                int currentCount = 1;
                char currentValue = number.charAt(0);
                for (int j=1; j<number.length(); j++) {
                    if (number.charAt(j) != currentValue) {
                        seqBuilder.append(currentCount);
                        seqBuilder.append(currentValue);
                        currentCount = 1;
                        currentValue = number.charAt(j);
                    }
                    else {
                        currentCount++;
                    }
                }
                seqBuilder.append(currentCount);
                seqBuilder.append(currentValue);
                number = seqBuilder.toString();
            }
            return number;
        }
    }
    

Log in to reply
 

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