Count and Say

本文介绍了一种生成计数与描述序列的算法实现,该序列从1开始,每一步通过对前一个序列进行计数和描述来生成新的序列。例如,1被描述为“one 1”即11,11被描述为“two 1s”即21等。通过两个循环和字符数组处理,实现了序列的高效生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第二篇~~~

这道题比较简单,很容易做出来,下面先说说我的做法~~

题目如下

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天~~但是我已经开始想你了~我跟你说过的话不只是说说而已~我确实在努力~相信我!~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值