My recursive Java solution


  • 0
    L
    public class Solution {
        public static String countAndSay(int n) {
            if(n <= 0) return "illegal input";
            else if(n == 1) return "1";
            else {
                String in = countAndSay(n-1);
                int count = 1;
                StringBuffer out = new StringBuffer();
                for(int i=0; i<in.length(); i++) {
                    char c = in.charAt(i);
                    if(i != in.length()-1 && c == in.charAt(i+1)) {
                        count++;
                    }
                    else {
                        out.append("" + count + c);
                        count = 1;
                    }
                }
            return out.toString();
            }
        }
    }

Log in to reply
 

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