The Count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1is read off as"one 1"Or11.
11is read off as"two 1s"Or21.
21is read off as"one 2, thenone 1"Or1211.
Given an integer n, generate the nth sequence.
Note:the sequence of integers would be represented as a string.
Analysis, the iteration solves the result of nth time, so starting with the first "1" iteration, the last resulting string is re-expressed in the above form
public class Solution {
Public String Countandsay (int n) {
if (n = = 1) {
return "1";
}
String s = "1";
StringBuffer ret = new StringBuffer ();
int cnt = 0;
int round = 0; How many times round is an iteration
int i;
while (++round < n) {
CNT = 1;
Ret.setlength (0);
for (I=1; I<s.length (); i++) {
if (S.charat (i) = = S.charat (i-1)) {//duplicate value, continue count
cnt++;
}else{//A new value appears, recorded to RET
Ret.append (CNT). Append (S.charat (i-1));
CNT = 1; Reset CNT
}
}
Ret.append (CNT). Append (S.charat (i-1));
s = ret.tostring (); Update S
}
return ret.tostring ();
}
}
Leetcode#38count and Say