Concise Java Solution


  • 0
    V
    public class Solution {
        public String countAndSay(int n) {
            StringBuilder last = new StringBuilder("1");
            
            for(int seqNum = 2; seqNum <= n; seqNum++) {
                StringBuilder next = new StringBuilder();
                char say = last.charAt(0);
                int count = 1;
                
                for (int i=1; i < last.length(); i++) {
                    if (last.charAt(i) == last.charAt(i - 1)) {
                        count++;
                    } else {
                        next.append(count);
                        next.append(say);
                        count = 1;
                        say = last.charAt(i);
                    }
                }
                
                next.append(count);
                next.append(say);
                last = next;
            }
            
            return last.toString();
        }
    }
    

Log in to reply
 

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