Recursive solution


  • 0
    T
    public class Solution {
        public String countAndSay(int n) {
            if (n == 1) {
                return "1";
            } else {
                return interpret(countAndSay(n-1));
            }
        }
        
        private String interpret(String number) {
            int counter = 0;
            String current = null;
            String solution = "";
            for (int i = 0; i < number.length(); i++) {
                if (current == null) {
                    current = number.charAt(i) + "";
                    counter = 1;
                } else if (current.equals(number.charAt(i)+"")) {
                    counter++;
                } else {
                    solution += counter + current;
                    counter = 1;
                    current = number.charAt(i) + "";
                }
            }
            if (current != null) {
            solution += counter + current;
            }
            return solution;
        }
    }
    

Log in to reply
 

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