My straightforward Java solution


  • 0
    Z
    class Solution {
        public String countAndSay(int n) {
            if (n == 1) return "1";
            StringBuilder pre = new StringBuilder("1");
            for (int i = 1; i < n; i ++) {
                StringBuilder sb = new StringBuilder();
                int count = 1;
                for (int j = 1; j < pre.length(); j++) {
                    if (pre.charAt(j) != pre.charAt(j - 1)) {
                        sb.append(String.valueOf(count)).append(pre.charAt(j - 1));
                        count = 1;
                    } else {
                        count++;
                    }
                }
                sb.append(String.valueOf(count)).append(pre.charAt(pre.length() - 1));
                pre = sb;
            }
            return pre.toString();
        }
    }
    

Log in to reply
 

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