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是个整数,迭代。
代码如下
需要注意的地方:
for循环附近。初始条件要处理好。迭代次数要想明白。
public class Solution {
public String countAndCount(String s){
char tmp = s.charAt(0);
String res = "";
int num = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if (ch == tmp){
num++;
}
else{
res = res + num + tmp;
tmp = ch;
num = 1;
}
}
res = res + num + tmp;
return res;
}
public String countAndSay(int n) {
String str = "1";
for(int i = 1; i < n; i++){
str = countAndCount(str);
}
return str;
}
}