Simple Java solution


  • 0
    M
    class Solution {
        public String countAndSay(int n) {
            if (n <= 0) return "";
            
            String s = "1";
            for (int i = 2; i <= n; i++) {
                int l = 0, r = 0;
                String ns = "";
                while (r < s.length()) {
                    if (s.charAt(l) != s.charAt(r)) {
                        ns += Integer.toString(r-l) + String.valueOf(s.charAt(l));
                        l = r;
                    }
                    r++;
                }
                ns = ns + Integer.toString(r-l) + String.valueOf(s.charAt(l));
                s = ns;
            }
            return s;
        }
    }
    

Log in to reply
 

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