Java solution (3 ms, beats 97.06%)


  • 0
    A
    public String countAndSay(int n) {
        String result = "1";
        if (n <= 1) {
          return result;
        }
        StringBuilder b = new StringBuilder();
        while (n-- > 1) {
          result = getWords(result, b);
        }
        return result;
      }
    
      private String getWords(String number, StringBuilder b) {
        b.setLength(0);
        char previous = number.charAt(0);
        int n = 1;
        for (int i = n; i < number.length(); i++, n++) {
          if (previous != number.charAt(i)) {
            b.append(n).append(previous);
            n = 0;
          }
          previous = number.charAt(i);
        }
        if (n != 0) {
          b.append(n).append(previous);
        }
        return b.toString();
      }
    

Log in to reply
 

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