Java - 4ms - Recursive


  • 0
    N
    public class Solution {
        public String countAndSay(int n) {
            return n < 2 ? "1" : run("1", n);
        }
        
        private String run(String prefix, int n) {
            return n == 1 ? prefix : run(transfer(prefix), n-1);
        }
        
        private String transfer(String raw) {
            StringBuilder builder = new StringBuilder();
            char c = raw.charAt(0);
            int count = 1;
            for (int i = 1; i < raw.length(); i++) {
                if(c == raw.charAt(i)){
                    count++;
                } else {
                    builder.append(count).append(c);
                    c = raw.charAt(i);
                    count = 1;
                }
            }
            return builder.append(count).append(c).toString();
        }
    }
    

Log in to reply
 

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