计数和说出序列是整数序列,开始如下:
1, 11, 21, 1211, 111221, ...
1
作为"one 1"
或读取11
。
11
作为"two 1s"
或读取21
。
21
正如读出"one 2
,则one 1"
或1211
。
给定整数n,生成第n 个序列。
注意:整数序列将表示为字符串。
算法逻辑:使用Java8
public static String countAndSay(int n) {
String ret = ""+1;
while(--n > 0)
ret = apply(ret);
return ret;
}
public static String apply(String s){
StringBuilder ret = new StringBuilder();
for(int i = 0, count =0; i < s.length() ; ){
while(i + count < s.length() && s.charAt(i) == s.charAt(i + count))
count ++;
ret.append(count).append(s.charAt(i));
i += count;
count = 0;
}
return ret.toString();
}