Solution beats 85%..Simple to understand!!!


  • 0
    A
    public class Solution {
        public String countAndSay(int n) {
            if (n <= 0){
                return "";
            }
            if (n == 1){
                return "1";
            }
            String res = "1";
            for (int i = 2; i <= n; i++){
                res = buildString(res);
            }
            return res;
        }
        
        public String buildString(String res){
            if (res == null || res.isEmpty()){
                return "";
            }
            StringBuilder subRes = new StringBuilder("");
            for (int i = 0; i < res.length(); i++){
                int count = 1;
                int j = i+1;
                while(j < res.length() && res.charAt(i) == res.charAt(j)){
                    count++;
                    j++;
                }
                i = j - 1;
                subRes.append(count);
                subRes.append(res.charAt(i));
            }
            return subRes.toString();
        }
    }

Log in to reply
 

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