比较相邻两个数是否相同,进而决定是移动下标,还是描述该项内容。
public String countAndSay(int n) {
StringBuilder builder = new StringBuilder();
StringBuilder seq = new StringBuilder();
builder.append("1");
int k = 1, i = 0, j = 0;
if (n > 1) {
for (i=2; i<= n; i++) {
k = 1;
for (j=0; j<builder.length(); j++) {
while (j+1 < builder.length() && builder.charAt(j) == builder.charAt(j+1)) {
k++;
j++;
}
if (j+1 < builder.length() && builder.charAt(j) != builder.charAt(j+1)) {
seq.append(k);
k = 1;
seq.append(builder.charAt(j));
}
if (j+1 == builder.length()) {
seq.append(k);
seq.append(builder.charAt(j));
}
}
builder = seq;
seq = new StringBuilder();
}
}
return builder.toString();
}