38. Count and Say - cocoder39/coco39_LC GitHub Wiki

38. Count and Say

class Solution:
    def countAndSay(self, n: int) -> str:

        s = '1'
        while n > 1:
            s = self.encode(s)
            n -= 1
        return s
    

    def encode(self, s: str):
        i = 0
        res = ''
        while i < len(s):
            start = i
            while i + 1 < len(s) and s[i + 1] == s[i]:
                i += 1
            res += str(i - start + 1) + s[start]
            i += 1
        return res
class Solution {
public:
    string countAndSay(int n) {
        if (n <= 0) {
            return "";
        } else if (n == 1) {
            return "1";
        } 
        
        string res = "1";
        for (int i = 1; i < n; i++) {
            res = helper(res);
        }
        return res;
    }
private:
    string helper(string& str) {
        string res;
        int i = 0;
        while (i < str.length()) {
            int start = i;
            for (; i < str.length() && str[i] == str[start]; i++)  ;
            res += to_string(i - start) + string(1,str[start]);
        }
        return res;
    } 
};