Readable Recursive Answer


  • 0
    A
    public class Solution
    {
        public String countAndSay(int n)
        {
            if (n == 0) return "";
            if (n == 1) return "1";
            return countAndSayHelper(n - 1, "1");
        }
        
        public String countAndSayHelper(int n, String prev)
        {
            if (n == 0) return prev;
    
            char[] s = prev.toCharArray();
            StringBuilder sb = new StringBuilder();
    
            for (int i = 0; i < s.length; i++)
            {
                int counter = 1;
                int j = i + 1;
                while (j < s.length && s[j] == s[i])
                {
                    j++;
                    counter++;
                }
                sb.append(Integer.toString(counter) + Character.toString(s[i]));
                if (counter > 1) i = j - 1;
            }
    
            return countAndSayHelper(n - 1, sb.toString());
        }
    }

Log in to reply
 

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