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.
Analysis:
The idea is simple, string operation. Compare current char with next char, if same count++, else record this to result.
Java
public String countAndSay(int n) {
String result = "1";
if(n==1) return result;
int level = 1;
while(level<n){
char last = result.charAt(0);
int count =0;
StringBuffer seq = new StringBuffer();
for(int i=0;i<result.length();i++){
if(last == result.charAt(i)){
count++;
continue;
}else {
seq.append(count);
seq.append(last);
last = result.charAt(i);
count=1;
}
}
seq.append(count);
seq.append(last);
result = seq.toString();
level++;
}
return result;
}c++
string countAndSay(int n) {
string result = "1";
int level = 1;
while(level < n){
stringstream seq;
char last = result[0];
int count =0;
for(int i=0; i<=result.size();i++){
if(result[i] == last){
count++;
continue;
}
else{
seq<<count<<last;
count = 1;
last = result[i];
}
}
result = seq.str();
level++;
}
return result;
}

本文介绍了一种基于字符串操作生成计数与描述序列的方法,通过比较当前字符与下一个字符来实现序列的生成。提供了 Java 和 C++ 的实现代码。
492

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



