描述
报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, ...
1 读作 "one 1" -> 11.
11 读作 "two 1s" -> 21.
21 读作 "one 2, then one 1" -> 1211.
报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, ...
1 读作 "one 1" -> 11.
11 读作 "two 1s" -> 21.
21 读作 "one 2, then one 1" -> 1211.
给定一个整数 n, 返回 第 n 个顺序。
样例
给定 n = 5, 返回 "111221".
实现:
public class Solution {
/**
* @param n: the nth
* @return: the nth sequence
*/
public String countAndSay(int n) {
if(n<1) return null;
String str="1";
n--;
while(n>0){
str=getNext(str);
n--;
}
return str;
}
public String getNext(String str){
StringBuilder sb=new StringBuilder();
int i=0;
while(i<str.length()){
char c=str.charAt(i);
int count=1;
i++;
while(i<str.length() && str.charAt(i)==c){
count++;
i++;
}
sb.append(count);
sb.append(c);
}
return sb.toString();
}
}