38. 报数

题目描述

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.

代码实现

class Solution {
public:
    string countAndSay(int n) {

    	if(n<=1)
    		return "1";
    	string cur = "1";
    	string next = "";
    	int k = 1;//k的含义为已经产生的序列的个数
    	while(k<n)
    	{   
            int len = cur.length();
    		int i =0;
    		while(i<len)
    		{
    			char c = cur[i];
    			int cnt = 1;
    			int j = i+1;
    			while(j<len && cur[j]==c)
    			{                    
    				cnt++;
    				j++;
    			}     //Java中对应的方法是.toString()
    			next+=to_string(cnt)+c;
    
    			i=j;
    		}
    		cur = next;
    		k++;
    		next = "";
    	}
    	return cur;       
    }

};

posted on 2021-04-04 13:53  朴素贝叶斯  阅读(21)  评论(0编辑  收藏  举报

导航