Saturday, April 18, 2015

Count and Say

Problem:

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.

Solution:
class Solution {
public:
    // Runs in 6ms
    string generate (string s) {
        string sol;
        int size = s.size();
        if (size == 0)
            return "1";
        int count = 1;
        for (int i = 0; i < size - 1; i++) {
            if (s[i] == s[i + 1])
                count++;
            else {
                sol += to_string(count);
                sol.push_back(s[i]);
                count = 1;
            }
        }
        sol += to_string(count);
        sol.push_back(s[size - 1]);
            
        return sol;
    }
    /*   // Runs in 4ms
    string generate (string s) {
        stringstream sol;
        int size = s.size();
        if (size == 0)
            return "1";
        int count = 1;
        for (int i = 0; i < size - 1; i++) {
            if (s[i] == s[i + 1])
                count++;
            else {
                sol << count << s[i];
                //sol.push_back(s[i]);
                count = 1;
            }
        }
        sol << count << s[size - 1];
            
        return sol.str();
    } */
    
    string countAndSay(int n) {
        string sol;
        
        for (int i = 1; i <= n; i++) {
            sol = generate(sol);
        }
        return sol;
    }
};

========= Third attempt =========

string countAndSay(int n) {
        if (n < 1) {
            return "";
        }
       
        string prev = "1";
        string ans;
        for (int i = 2; i <= n; i++) {
            int count = 1;
            for (int j = 0; j < prev.size() - 1; j++) {
                if (prev[j] == prev[j + 1]) {
                    count++;
                } else {
                    ans += to_string(count) + string(1, prev[j]);
                    count = 1;
                }
            }
            ans += to_string(count) + string(1, prev[prev.size() - 1]);
            prev = ans;
            ans.clear();
        }
       
        return prev;
    }

No comments:

Post a Comment