第二篇~~~
这道题比较简单,很容易做出来,下面先说说我的做法~~
题目如下
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.
我的方法是用了两个循环,在第二个循环中用step计算数字重复次数,遇到不重复的数字则跳出同时step置为1,同时更新结果字符串。此过程重复n次后得到最终结果。public String countAndSay(int n) {
String temp = "";
String seq = "1";
char[] str2char;
int i = 1;
int step = 0;
while(i != n) {
temp = "";
str2char = seq.toCharArray();
for(int p = 0 ; p < str2char.length; p += step) {
step = 1;
for(int q = p + 1 ; q < str2char.length ; ++q) {
if(str2char[p] == str2char[q])
step++;
else
break;
}
temp += step + "" + str2char[p];
}
i++;
seq = temp;
}
return seq;
}以上是第二篇~~道路仍在继续~~
还有不到5天~~但是我已经开始想你了~我跟你说过的话不只是说说而已~我确实在努力~相信我!~~
本文介绍了一种生成计数与描述序列的算法实现,该序列从1开始,每一步通过对前一个序列进行计数和描述来生成新的序列。例如,1被描述为“one 1”即11,11被描述为“two 1s”即21等。通过两个循环和字符数组处理,实现了序列的高效生成。
493

被折叠的 条评论
为什么被折叠?



