Java solution that runs in 4ms


  • 0
    T
        public String countAndSay(int n) {
            String s = "1";
            while (n-- > 1) {
                final char[] chars = s.toCharArray();
                int cnt = 0, j = 0;
                char prevc = chars[0];
                final StringBuilder p = new StringBuilder();
                for (char c : chars) {
                    if (c == prevc) cnt++;
                    else {
                        p.append(cnt).append(prevc);
                        cnt=1;
                    }
                    if (j++ == chars.length-1) {
                        p.append(cnt).append(c);
                    }
                    prevc = c;
                }
                s=p.toString();
            }
            return s;
        }
    

Log in to reply
 

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