参考:http://blog.csdn.net/linhuanmars/article/details/20679963
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.
实际在跑的时候,内层的循环当进行到最后一次的时候,只会计数而不会往res上添加结果,所以要在内层循环外再补上。
代码:
package leetcode;
public class CountAndSay {
public static void main(String args[]){
System.out.println(new CountAndSay().countAndSay(4));
}
public String countAndSay(int n) {
if (n < 0)
return "";
String curRes = "1";
for (int i = 2; i <= n; i++) {
int count = 1;
String res = "";
for (int j = 1; j < curRes.length(); j++) {
if (curRes.charAt(j - 1) == curRes.charAt(j)) {
count++;
} else {
res += count;
res += curRes.charAt(j - 1);
count = 1;
}
}
//举个例子就懂了..
res += count;
res += curRes.charAt(curRes.length()-1);
curRes = res;
}
return curRes;
}
}