1. 1
2. 11
3. 21
4. 1211
5. 111221
第一项是数字 1
描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"
描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"
描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"
描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"

示例 1:
示例 2:
package String;
/**
* @Author: IronmanJay
* @Description: 38.外观数列
* @CreateTime: 2022-12-02 09:53
*/
public class p38_CountAndSay {
public static void main(String[] args) {
int n = 4;
String res = countAndSay(n);
System.out.println("res = " + res);
}
public static String countAndSay(int n) {
String str = "1";
for (int i = 2; i <= n; i++) {
StringBuffer sb = new StringBuffer();
int start = 0;
int pos = 0;
while (pos < str.length()) {
while (pos < str.length() && str.charAt(start) == str.charAt(pos)) {
pos++;
}
sb.append(Integer.toString(pos - start));
sb.append(str.charAt(start));
start = pos;
}
str = sb.toString();
}
return str;
}
}
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
char * countAndSay(int n)
{
char* str = (char*)malloc(sizeof(char) * 5001);
str[0] = '1';
str[1] = '\0';
for (int i = 2; i <= n; i++)
{
char* temp = (char*)malloc(sizeof(char) * 5001);
int pos = 0;
for (int j = 0; j < strlen(str); j++)
{
int count = 1;
while (str[j + 1] && str[j] == str[j + 1])
{
count++;
j++;
}
temp[pos++] = count + 48;
temp[pos++] = str[j];
temp[pos] = '\0';
}
strcpy(str, temp);
}
return str;
}
/*主函数省略*/
Java语言版

C语言版
