Recursion way in Java


  • 0
    C
    public class Solution {
        private String[] inits = new String[] {"1", "11", "21", "1211", "111221"};
        
        public String countAndSay(int n) {
            if(n < 6) return inits[n-1];
            String tmp = countAndSay(n-1);
            String rs = "";
            for(int i=0; i<tmp.length(); ) {
                int k = i;
                while(k<tmp.length() && tmp.charAt(k) == tmp.charAt(i)) k++;
                rs += "" + (k-i) + tmp.charAt(i);
                i = k;
            }
            return rs;
        }
    }
    

Log in to reply
 

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