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.

这道题看着挺复杂,但其实还是比较简单的,初始字符串为“1”,然后循环n-1次,每次循环产生一个新的字符串作为下一次循环时的读取的对象,每次从头开始读取字符串前k个相同的字符,将其个数和字符写入新的字符串,并对当前字符串进行截取(去掉已经读取过的字符),直到当前字符串为空串一次循环结束并开始新的循环,最后一次循环结束后得到最终结果。

class Solution {
public:
    string countAndSay(int n) {
        string s = "1";
		for(int i = 2; i <= n; i++){			
			string temp;			
			while(!s.empty()){
				char c = s.front();
				int count = 0;
				for(int k = 0; k < s.length(); k++){
				    if(s[k] != c)
						break;
					count++;
				}
				char cCount = count + '0';
				temp.append(1,cCount);
				temp.append(1,c);
				s = s.substr(count);
			}
			s = temp;
		}
		return s;
    }
};

这道题的重点是掌握对字符串的截取及追加等操作,以及字符数字之间的转换。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值