程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Leetcode 模擬 Count and Say

Leetcode 模擬 Count and Say

編輯:C++入門知識

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;
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved