您的位置:首页 > 其它

LeetCode 38 Count and Say

2016-03-30 15:16 253 查看
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 static String countAndSay(int n) {
if (n == 0) return null;
String[] nums = new String[n - 1];
nums[0] = "1";
for (int i = 0; i < n - 1; i++) {
int count = 0;
char num = nums[i].charAt(0);
StringBuffer say = new StringBuffer("");
for (int j = 0; j < nums[i].length(); j++) {
if (nums[i].charAt(j) == num)
count++;
else {
say.append(count).append(num);
num = nums[i].charAt(j);
count = 1;
}
}
nums[i + 1] = say.append(count).append(num).toString();
}
return nums[n - 1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: