Clear and concise Java solution using recursion


  • 1
    L
    public class Solution {
        public String countAndSay(int n) {
            
            // sanity check
            if (n <= 0) return null;
            
            // base case
            if (n == 1) return "1";
            
            String str = countAndSay(n-1);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < str.length(); i++) {
                int count = 1;
                while (i < str.length()-1 && str.charAt(i) == str.charAt(i+1)) {
                    count++;
                    i++;
                }
                sb.append(count).append(str.charAt(i));
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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