Clean Java Code


  • 0
    class Solution {
        public String countAndSay(int n) {
            String res = "1";
            while (--n > 0) {
                res = count(res);
            }
            return res;
        }
        
        public String count(String str) {
            StringBuilder sb = new StringBuilder();
            char[] chars = str.toCharArray();
            char curr = 'a';
            int cnt = 0;
            for (char c : chars) {
                if (c == curr) {
                    cnt++;
                } else {
                    if (cnt != 0) {
                        sb.append(cnt + "" + curr);    
                    }
                    curr = c;
                    cnt = 1;
                }
            }
            sb.append(cnt + "" + curr);
            return sb.toString();
        }
    }
    

Log in to reply
 

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