Count and Say


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:

Two approaches to concatenate string with integer

1. use #include<sstream>, and then define a stringstream class.

2. use method push_back to append the char (result.push_back('0' + count);).

The following code passes LeetCode Online Large Judge.

class Solution {
public:
    string countAndSay(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string result, tmp;
        if (n < 1) return result;
        int i = 0;
        while (i < n) {
            tmp = result;
            result = helper(tmp);
            i++;
        }
        return result;
    }
    
    string concatenate(string s, int i)
    {
        stringstream ss;
        ss << s << i;
        return ss.str();
    }
    
    string helper(string s) {
        string result;
        if (s.empty()) {
            result += '1';
            return result;
        }
        if (s.size() == 1) {
            result += '1';
            result += s[0];
            return result;
        }
        char tmp = s[0];
        int i = 1, ctr = 1;
        while (i < s.size()) {
            if (s[i] != s[i-1]) {
                result = concatenate(result, ctr);
                result += s[i-1];
                ctr = 0;
            }
            ctr++;
            i++;
        }
        result = concatenate(result, ctr);
        result += s[i-1];
        return result;
    }
};

Comments

Popular posts from this blog

Maximum Gap

[ITint5] Maximum Subarray for a Circular Array

[CC150] Chapter 4 Trees and Graphs