Share my Recursive JAVA solution


  • 1
    W
    public class Solution {
        public String countAndSay(int n) {
            if (n == 1) return "1";
            return say(countAndSay(n - 1));
        }
        private String say(String str){
            StringBuilder res = new StringBuilder();
            int count = 1;
            char[] ca = str.toCharArray();
            char current = ca[0];
            for (int i = 1; i < ca.length; i++){
                if (ca[i] == current){
                    count++;
                } else {
                    res.append(count);
                    res.append(current);
                    count = 1;
                    current = ca[i];
                }
            }
            res.append(count);
            res.append(current);
            return res.toString();
        }
    }

Log in to reply
 

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