Java solution, easy to understand, recursive, beating 90%


  • 0

    Very fast, really easy to understand with comments.

    public class Solution {
        public String countAndSay(int n) {
            // recursive base
            if (n == 1) return "1";
            
            // get the previous string
            String s = countAndSay(n-1);
            StringBuilder sb = new StringBuilder();
            
            // first number
            char num = s.charAt(0);
            int count = 1;
            for (int i = 1; i < s.length(); ++i) {
                if (s.charAt(i) != s.charAt(i-1)) {
                    // different, say the previous count and number
                    sb.append(count).append(num);
                    
                    // save current number, reset counter to one
                    num = s.charAt(i);
                    count = 1;
                } else {
                    // save, increase count
                    count++; 
                }
            }
            sb.append(count).append(num);
            return sb.toString();
        }
    }
    

Log in to reply
 

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