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;
那么接着下面就是一个1:11
接着:2个1:21
接着一个2一个1:1211
public class Solution {
public String countAndSay(int n) {
int[] str = new int[n * 10000];
int[] str1 = new int[n * 10000];
str1[0] = 1;
int strLen = 1;
int k;
for (int i = 1; i < n; ++i) {
int pre = 0, next = 0;
k = 0;
while (next < strLen) {
while (next < strLen && str1[pre] == str1[next]) {
++next;
}
int count = next - pre;
int sign = str1[pre];
int[] vec = new int[100];
int vecLen = 0;
while (count != 0) {
vec[vecLen++] = count % 10;
count /= 10;
}
while (vecLen >= 1) {
str[k++] = vec[--vecLen];
}
str[k++] = sign;
pre = next;
}
int[] t = str1;
str1 = str;
str = t;
strLen = k;
// System.out.println(k);
}
StringBuilder sb = new StringBuilder(strLen);
for (int i = 0; i < strLen; ++i) {
sb.append(str1[i]);
}
return sb.toString();
}
}