Tuesday, July 7, 2015

Leetcode 38: 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.

这题属于string compress类型的,记录每个char出现的次数,做这题的时候花了很多时间,一开始想用constant memory来做,不另声明一个string,但是这样做下来很麻烦,需要考虑string long to short 和 string short to long,用slow, fast来处理string。但是在网上看了别人做的答案,都重声明了string,因为题目没有要求用constant memory 来做。
time complexity: O(n) space complexity: O (n)
class Solution {
public:
    string countAndSay(int n) {
        if (n < 1) return "";
        if (n == 1) return "1";
        string ini = "1";
        int count = 0;
        for (int i = 1; i < n; i++) {
            string tmp = "";
            for (int j = 0; j < ini.size(); j++) {
                char c = ini[j];
                while (j < ini.size() && c == ini[j]){
                    count++;
                    j++;
                }
                tmp += count + '0';
                tmp += c;
                count = 0;
                j--;
            }
            ini =  tmp;
        }
        return ini;
    }
};

No comments:

Post a Comment