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 string countAndSay(int n) { 2 // Note: The Solution object is instantiated only once and is reused by each test case. 3 string s = "1", t; 4 if(n == 1) 5 return s; 6 int i, j; 7 for(i = 1; i < n; i++){ 8 t = ""; 9 int l = s.length(); 10 for(j = 0; j < l; j++){ 11 if(((j+1<l)&&s[j+1]!=s[j]) || (j+1 >= l)){ 12 t += '1'; 13 t += s[j]; 14 } 15 else{ 16 int num = 1; 17 while((j+num<l) && (s[j+num]==s[j])){ 18 num++; 19 } 20 j+=(num-1); 21 if(num>999){ 22 t += (char)(num/1000 + '0'); 23 num = num%1000; 24 } 25 if(num>99){ 26 t += (char)(num/100 + '0'); 27 num = num%100; 28 } 29 if(num>9){ 30 t += (char)(num/10 + '0'); 31 num = num%10; 32 } 33 t += (char)(num + '0'); 34 t += s[j]; 35 } 36 } 37 s = t; 38 } 39 return s; 40 }
第二遍
1 string countAndSay(int n) { 2 string result = "1"; 3 if(n == 1) 4 return result; 5 string next; 6 int i,j,k; 7 for(i = 2; i <= n; i++){ 8 j = 0; 9 while(j < result.length()){ 10 k = j+1; 11 while(k < result.length() && result[k] == result[j]) 12 k++; 13 next += (k-j+'0'); 14 next += result[j]; 15 j = k; 16 } 17 result = next; 18 next = ""; 19 } 20 return result; 21 }