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.
public String countAndSay(int n) {
String init = "1";
for (int i = 1; i < n; i++) {
init = countAndSay(init);
}
return init;
}
String countAndSay(String string) {
char[] str = string.toCharArray();
String s = "";
int p = 1;
int count = 1;
char last = str[0];
for (; p < str.length; p++) {
if (str[p] == last) {
count++;
} else {
s += "" + count + last;
count = 1;
last = str[p];
}
}
s += "" + count + last;
return s;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。