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.valueOf()方法。
public class Solution {
public String countAndSay(int n) {
String str = "1";
for (int i = 1; i < n; i++) {
str = solve(str);
}
return str;
}
public String solve(String str) {
String result = "";
char ch = str.charAt(0);
System.out.println(ch);
int count = 1;
for (int i = 1; i < str.length(); i++) {
char c = str.charAt(i);
if (ch == c) {
count++;
} else {
char t = (char) (count + '0');
result += String.valueOf(t) + String.valueOf(ch);
ch = c;
count = 1;
}
}
char t = (char) (count + '0');
result += String.valueOf(t) + String.valueOf(ch);
return result;
}
}

本文介绍了一种生成计数与描述序列的方法,通过递归生成字符串的方式实现了给定整数n时生成对应的序列。文章提供了详细的Java实现代码,帮助读者理解如何通过字符计数并转换为字符串来形成序列。

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



