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.
String
Code in Java:
public class Solution {
public String countAndSay(int n) {
String prevS="1";
String curS="1";
for(int i=1; i<n; i++){
curS="";
char prevC=prevS.charAt(0), curC=prevS.charAt(0);
int dup=1;
for(int j=1; j<prevS.length();j++){
curC=prevS.charAt(j);
if(curC==prevC) dup++;
else{
curS = curS+String.valueOf(dup)+prevC;
dup=1;
prevC=curC;
}
}
curS = curS+String.valueOf(dup)+curC;
prevS=curS;
}
return curS;
}
}

本文详细解析了Count-and-Say序列的生成原理,通过实例代码演示了如何利用Java实现该序列的生成过程。
1299

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



