设为首页 加入收藏

TOP

Leetcode 模拟 Count and Say
2015-07-20 17:44:16 来源: 作者: 【 】 浏览:2
Tags:Leetcode 模拟 Count and Say

Count and Say

Total Accepted: 14508 Total Submissions: 53213My Submissions

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,11,21,1211,111221,...
它是这样产生的:
1读作 ‘one 1’,即 11
11读作 'two 1s',即 21
21读作 'one 2 one 1',即1211
...
给定整数 n,返回该序列的第 n 个数
思路:模拟
复杂度:时间O(n),空间O(1)


//一般写法
string countAndSay(int n){
	string last = "1";
	while(--n){
		int count = 1;
		char c = last[0];
		string cur;
		for(int i = 1; i <= last.size(); ++i){
			if(i < last.size() && last[i] == c) count++;
			else{
				cur += count + '0';
				cur += c;
				if(i < last.size()){
					count = 1;
					c = last[i];
				}
			}
		}
		last = cur;
	}
	return last;
}
//使用stl
string countAndSay(int n){
	string past = "1";
	while(--n){
		string cur;
		for(auto iter = past.begin(); iter != past.end();){
			auto iter2 = find_if(iter, past.end(), bind1st(not_equal_to
  
   (), *iter));
			cur += distance(iter, iter2) + '0';
			cur += *iter;
			iter = iter2;
		}
		past = cur;
	}
	return past;
}
  


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇ZOJ 3818 Pretty Poem 模拟题 下一篇ZOJ-3811 Untrusted Patrol DFS 2..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)