leetcode 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.

 

Subscribe to see which companies asked this question

 
 
从十七号早晨想了十七号一天,今天早上也在想。就这么一道题。就是没想出来,这种挫败感。
用vector想了,栈想了,列表都想了,却单单没有想简单的用string实现。
 
首先,扫描一个字符串,然后把次数和字符按顺序加入到一个新的字符串中,应该是一个独立函数的功能。
其次,n应该是执行这个函数的一个循环次数,初始的字符串应该是“1”
 
学习了~~以后这种题要注意。
class Solution {
public:
    string Ustring(string s){   //扫描一个字符串,
        int count=1;
        string ret;
        char tmp;
        char stmp=s[0];
        for(int i=1;i<s.length();i++){
            if(s[i]==stmp) {
                count++;
            }else {
                tmp=count+'0';
                ret=ret+tmp+stmp;
                stmp=s[i];
                count=1;
            }
        }
        tmp=count+'0';
        ret=ret+tmp+stmp;
        return ret;
    }
    
    string countAndSay(int n) {
        string s="1";
        for(int i=1;i<n;i++){
            s=Ustring(s);
        }
        return s;
        
    }
};

 

 
posted @ 2015-12-18 21:38  0giant  阅读(175)  评论(0编辑  收藏  举报