Leetcode Count and Say

来源:互联网 发布:手机淘宝掌柜热卖在哪 编辑:程序博客网 时间:2024/06/05 05:52

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.

原题:点击打开链接

class Solution {public:    string countAndSay(int n){        string s = "1";        while(--n > 0){            string tmp;            tmp.clear();                        int size = s.length(), cnt = 1;            char lastChar = s[0];                        for(int i=1;i<size;i++){                if(lastChar == s[i]){                   cnt++;                        }else{                   tmp += cnt + '0';                   tmp += lastChar;                   lastChar = s[i];                   cnt = 1;                }            }                        tmp += cnt + '0';            tmp += lastChar;            s = tmp;        }        return s;    }};


0 0
原创粉丝点击