4ms Solution in Java


  • 0
    J

    Hope it helps.

    class Solution {
        public String countAndSay(int n) {
            String answer = "1";
            StringBuilder builder = new StringBuilder();
            while (--n > 0) {
                int count = 0;
                char pre = 0;
                for (int i = 0; i < answer.length(); i++) {
                    if (pre == 0 || answer.charAt(i) == pre) {
                        count++;
                        pre = answer.charAt(i);
                    } else {
                        builder.append(count).append(pre);
                        pre = answer.charAt(i);
                        count = 1;
                    }
                }
                builder.append(count).append(pre);
                answer = builder.toString();
                builder.setLength(0);
            }
            return answer;
        }
    }
    

Log in to reply
 

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