[LeetCode] Count and Say

2014-11-24 02:21:06 · 作者: · 浏览: 1
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.
问题描述:count-and-say序列是如上所示的序列,比如,1,可以读作1个1, 所以下一个数就是11,11可以读作2个1,所以,下一个就是21。给定一个整数n,生成序列的第n个整数序列,该整数序列表示为字符串。
该题可以采用计数的方式,依次遍历,比如1211,1个1,就将整数1转换为字符,然后将11添加到结果字符串中,1个2,就将1转换为字符,然后将12添加到结果字符串中,2个1,将2转换为字符,然后将21添加到结果字符串中。
这道题关键的是要处理好边界情况。
class Solution {  
public:  
    string countAndSay(int n) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        int cnt = 0, i = 0, icnt = 0;  
        string s("1"), str;  
  
        for(cnt = 1; cnt < n; ++cnt) {  
            icnt = 0;  
            if(s.size() == 1) {  
                s.append(1, '1');  
                continue;  
            }  
            for(i = 1; i < s.size(); ++i) {  
                if(s.at(i-1) != s.at(i) && i != s.size()-1) {  
                    ++icnt;  
                    str.append(1, static_cast
(icnt)+48); str.append(1, s.at(i-1)); icnt = 0; } else if(s.at(i-1) != s.at(i) && i == s.size()-1) { ++icnt; str.append(1, static_cast(icnt)+48); str.append(1, s.at(i-1)); str.append(1, '1'); str.append(1, s.at(i)); } else if(s.at(i-1) == s.at(i) && i != s.size()-1) { ++icnt; } else if(s.at(i-1) == s.at(i) && i == s.size()-1) { icnt += 2; str.append(1, static_cast(icnt)+48); str.append(1, s.at(i-1)); } } s = str; str.clear(); } return s; } };