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.
模拟过程:
public String countAndSay1(int n) {
if(n<1) {
return "";
}
String result = "1";
for(int i=2; i<=n; i++) {
int num = 1;
String temp = "";
char c = result.charAt(0);
for(int j=1; j<result.length(); j++) {
if(result.charAt(j)==c) {
num++;
} else {
temp += String.valueOf(num);
temp += c;
c = result.charAt(j);
num = 1;
}
}
temp += String.valueOf(num);
temp += c;
result = temp;
}
return result;
}
public String countAndSay(int n) {
if(n<1) {
return "";
}
String result = "1";
for(int i=2; i<=n; i++) {
String temp = "";
char[] oldChars = result.toCharArray();
for(int k=0; k<oldChars.length; k++) {
int count = 1;
while((k+1)<oldChars.length &&
oldChars[k]==oldChars[k+1]) {
count++;
k++;
}
temp += (String.valueOf(count) + String.valueOf(oldChars[k]));
}
result = temp;
}
return result;
}