My Java Solution


  • 0
    H
    class Solution {
        public String countAndSay(int n) {
            String curr = "1";
            for (int i = 2; i <= n; i++) {
                StringBuilder next = new StringBuilder();
                char val = curr.charAt(curr.length() - 1);
                int count = 1;
                next.insert(0, val);
                for (int j = curr.length() - 2; j >= 0; j--) {
                    if (curr.charAt(j) != val) {
                        next.insert(0, count);
                        val = curr.charAt(j);
                        next.insert(0, val);
                        count = 1;
                    } else {
                        count++;
                    }
                }
                next.insert(0, count);
                curr = next.toString();
            }
            return curr;
        }
    }
    

Log in to reply
 

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