Monday, November 25, 2013

LeetCode Problem : 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.

Code

string numToStr(int n)
{
    stack<int> st;
    string result;
    while(n != 0){
        st.push(n % 10);
        n /= 10;
    }
    while(!st.empty()){
        result += st.top() + '0';
        st.pop();
    }
    return result;
}
string cas(const string& s)
{
    int n = s.size();
    int i = 0;
    string result;
    while(i<n){
        int j = i + 1;
        while(j < n && s[i] == s[j])
        ++j;
        int count = j - i;
        result += numToStr(count);
        result += s[i];
        i = j;
    }
    return result;
}
string countAndSay(int n) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    if(n == 1)
        return "1";
    string result = countAndSay(n - 1);
    return cas(result);
}

No comments:

Post a Comment