您的位置:首页 > 其它

LeetCode:Count and Say

2015-11-24 16:44 405 查看


Count and Say

My Submissions

Question

Total Accepted: 62217 Total
Submissions: 233796 Difficulty: Easy

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.

题意:

第1个数:1

第2个数:从前一个数来,上一个数是1个1,故:11

第3个数:上一个数是2个1,故:21

第4个数:上一个数是1个2 + 1个1,故:1211

...

求第n个数。

code:

class Solution {
public:
    string countAndSay(int n) {
        
        string s[2];
        s[0]="1";
        s[1]="";
        int cur=0;
        for(int i=1;i<n;i++) {
            
            int cnt;
            for(int j=0;j<s[cur].size();j+=cnt) {
                cnt=0;
                char t=s[cur][j];
                for(int k=j;k<s[cur].size() && t==s[cur][k];k++) cnt++;
                s[cur^1]+='0'+cnt;
                s[cur^1]+=t;
            }
            s[cur]="";
            cur^=1;
        }
        return s[cur];
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: