Java accepted solution


  • 0
    I
    public class Solution {
        public String countAndSay(int n) {
            if(n <= 0) return "";
            String ans = "1";
            for(int i = 1; i < n; i++) {
                ans = getSay(ans);
            }
            return ans;
        }
        
        public String getSay(String pre) {
            StringBuilder sb = new StringBuilder();
            int count = 1;
            char ch = pre.charAt(0);
            for(int i = 1; i < pre.length(); i++) {
                if(pre.charAt(i) == pre.charAt(i-1)) {
                    count++;
                } else {
                    sb.append(count).append(ch);
                    count = 1;
                    ch = pre.charAt(i);
                }
            }
            sb.append(count).append(ch);
            return sb.toString();
        }
    }
    

Log in to reply
 

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