Recursive Java Solution


  • 0
    C
    public class Solution {
        public String countAndSay(int n) {
            return countAndSay(n - 1, "1");
        }
        
        public String countAndSay(int n, String sequence) {
            if (n == 0) {
                return sequence;
            }
            
            StringBuilder nextSequence = new StringBuilder();
            for (int i = 0; i < sequence.length(); ) {
                char currentInt = sequence.charAt(i);
                int count = 1;
    
                // Count the number of consecutive times this digit appears
                while ((++i < sequence.length()) && (sequence.charAt(i) == currentInt)) {
                    count++;
                }
    
                nextSequence.append(count).append(currentInt);
            }
            
            return countAndSay(n - 1, nextSequence.toString());
        }
    }

Log in to reply
 

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