PAT甲级——A1140 LookAndSaySequence【20】
Look-and-say sequence is a sequence of integers as the following:
D, D1, D111, D113, D11231, D112213111, ...
where D
is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D
in the 1st number, and hence it is D1
; the 2nd number consists of one D
(corresponding to D1
) and one 1 (corresponding to 11), therefore the 3rd number is D111
; or since the 4th number is D113
, it consists of one D
, two 1's, and one 3, so the next number must be D11231
. This definition works for D
= 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D
.
Input Specification:
Each input file contains one test case, which gives D
(in [0, 9]) and a positive integer N (≤ 40), separated by a space.
Output Specification:
Print in a line the Nth number in a look-and-say sequence of D
.
Sample Input:
1 8
Sample Output:
1123123111
Solution:
能不能读懂这道题是个关键
举例序列:
D D1 D111 D113 D11231
解释:
D 怎么得到 D1
D中有 D 1个 ==》 D1
D1怎么得到D111
D1中有D 1个,1 1个 ==> D1 11 D111
D111怎么得到D113
D111中有D1个,1 3个 ==》 D1 13 D113
记住,D是输入的那个数字!!!!!我就没想通这点,坑死了
1 #include <iostream> 2 #include <string> 3 using namespace std; 4 int main() 5 { 6 string s; 7 int n; 8 cin >> s >> n; 9 for (int cnt = 1; cnt < n; ++cnt) 10 { 11 string str = ""; 12 int k; 13 for (int i = 0; i < s.length(); i=k)//计算各个字母出现的个数, i=k,从不重复的字母开始 14 { 15 for (k = i; k < s.length() && s[k] == s[i]; ++k);//计算相同的字母个数 16 str += s[i] + to_string(k - i);//将计算的该字母和其相同的次数算入 17 } 18 s = str; 19 } 20 cout << s; 21 return 0; 22 }