Java Recursive Solution


  • 0
    G
    • Based on the description, term n equals to "read off" of term n -1
    • e.g. 1 -> 11 ( read off 1 : one 1) -> 21 (read off 11 : two 1) -> 1211 (read off 21 : one 2 one 1)
    public class Solution {
        public String countAndSay(int n) {
           if ( n <= 1) return "1";
           return say(countAndSay(n - 1));
        }
    
        private String say(String s){
            char[] c = s.toCharArray();
            StringBuilder toReturn = new StringBuilder();
            
            char cur = c[0];
            int count = 0;
            for (int i = 0; i < c.length; i++){
                if (cur == c[i]) count++;
                else {
                    toReturn.append(Integer.toString(count)).append(cur);
                    count = 1;
                    cur = c[i];
                }
            }
            return toReturn.append(Integer.toString(count)).append(cur).toString();
        }
    }
    

Log in to reply
 

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