Count and Say

medium string

Problem

The count-and-say sequence starts with "1". Each subsequent term is generated by reading the previous term and saying it: count consecutive equal digits and write "count digit". Return the n-th term.

Inputn = 4
Output"1211"
1 → 11 → 21 → 1211.

def count_and_say(n):
    s = "1"
    for _ in range(n - 1):
        out, i = [], 0
        while i < len(s):
            j = i
            while j < len(s) and s[j] == s[i]:
                j += 1
            out.append(str(j - i) + s[i])
            i = j
        s = "".join(out)
    return s
function countAndSay(n) {
  let s = "1";
  for (let k = 1; k < n; k++) {
    let out = "", i = 0;
    while (i < s.length) {
      let j = i;
      while (j < s.length && s[j] === s[i]) j++;
      out += (j - i) + s[i];
      i = j;
    }
    s = out;
  }
  return s;
}
class Solution {
    public String countAndSay(int n) {
        String s = "1";
        for (int k = 1; k < n; k++) {
            StringBuilder sb = new StringBuilder();
            int i = 0;
            while (i < s.length()) {
                int j = i;
                while (j < s.length() && s.charAt(j) == s.charAt(i)) j++;
                sb.append(j - i).append(s.charAt(i));
                i = j;
            }
            s = sb.toString();
        }
        return s;
    }
}
string countAndSay(int n) {
    string s = "1";
    for (int k = 1; k < n; k++) {
        string out;
        int i = 0;
        while (i < (int)s.size()) {
            int j = i;
            while (j < (int)s.size() && s[j] == s[i]) j++;
            out += to_string(j - i) + s[i];
            i = j;
        }
        s = out;
    }
    return s;
}
Time: O(n · |sₙ|) Space: O(|sₙ|)