您的位置:首页 > 其它

[Leetcode 38, Easy] Count and Say

2015-02-12 13:25 288 查看
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.

Analysis:
This problem comes from a problem of Conwey (See http://en.wikipedia.org/wiki/Look-and-say_sequence ). The basic idea to this problem is back-tracking. Starting from the last entry of the array, if the previous one is the same
with the current one, then begin to count; otherwise, the number of this entry is only 1. Notice that the numbers in the array cannot be greater than 3. This is because the duplicated enties will be reduced at once, once the num of duplicates is greater than
1.

The analysis of running time is O(n) for each round of searching.

Solutions:

C++:

string Say(string count)
    {
        string rStr;
        rStr.push_back('0' + count.size());
        rStr.push_back(count[0]);
        return rStr;
    }
    
    string countAndSay(int n) {
        string str = "1";
        string prevSaying;
        prevSaying = str;
        if(n == 0)
            return str;
        
        for(int i = 1; i < n; ++i) {
            str.clear();
            if(i == 1) {
                prevSaying = Say(prevSaying);
                continue;
            }
            
            for(int j = prevSaying.size() - 1; j >= 0;) {
                if(j == 0) {
                    str.insert(0, Say(prevSaying.substr(0, 1)));
                    --j;
                } else {
                    int size = 1;
                    for(;j > 0 && prevSaying[j - 1] == prevSaying[j]; --j)
                        ++size;
                    str.insert(0, Say(prevSaying.substr(j >= 0 ? j : 0, size)));
                    --j;
                }
            }

            prevSaying = str;
        }

        return prevSaying;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: