Easy to understand JAVA solution 5ms


  • 0
    M
    public class Solution {
        public String countAndSay(int n) {
            if(n == 0) return "";
            String cur = "1";
            if(n == 1) return cur;
            while(n-- > 1) {
                int count = 1;
                char curChar = cur.charAt(0);
                StringBuilder temp = new StringBuilder();
                for(int i = 1; i < cur.length(); i++) {
                    if(cur.charAt(i) == curChar) count++;
                    else {
                        temp.append(count).append(curChar);
                        count = 1;
                        curChar = cur.charAt(i);
                    }
                }
                temp.append(count).append(curChar);
                cur = temp.toString();
            }
            return cur;
        }
    }
    

Log in to reply
 

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