Simple JAVA solution


  • 0
    Y

    I think most people use the similar way.any question or suggestion is welcomed.
    Here is my code.

    public  String countAndSay(int n){
            String lastNum  = "1";
            for(int i  = 1; i <= n - 1 ; i++){
                StringBuilder sb = new StringBuilder();
                char[] chars = lastNum.toCharArray();
                char cur = chars[0];
                int times = 0;
                for(int j = 0; j < lastNum.length(); j++){
                    if(chars[j] == cur)
                        times ++;
                    else {
                        sb.append(times).append(cur);
                        cur = chars[j];
                        times = 1;
                    }
                    if(j == lastNum.length() - 1){
                        sb.append(times).append(cur);
                    }
                }
                lastNum = sb.toString();
            }
            return lastNum;
        }

Log in to reply
 

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