Simple Recursive Java Solution (1 Helper Function)


  • 1
    L
    public class Solution {
        public String countAndSay(int n) {
            if (n == 1) return "1";
    
            return countAndSay(countAndSay(n - 1));
    
        }
    
        public String countAndSay(String num)
        {
            StringBuilder result = new StringBuilder();
            char c = num.charAt(0);
            int count = 1;
            for (int i = 1; i < num.length(); i++)
            {
                if (num.charAt(i) == c)
                    count++;
                else
                {
                    result.append(count).append(c);
                    c = num.charAt(i);
                    count = 1;
                }
            }
    
            result.append(count).append(c);
            return result.toString();
        }
    }

Log in to reply
 

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