Count and Say@leetcode

本文介绍了一种基于LeetCode的“计数并说”序列生成算法,通过具体实例解析了算法实现过程,并提供了完整的Java代码实现。

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

leetcode原题的地址链接:https://oj.leetcode.com/problems/count-and-say/


题目内容如下:

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.



题目翻译:

题目的意思就是

1    可以读成 1个1, 所以下一个数是11

11  可以读成2个1,所以下一个数是21

21 可以读成1个2,1个1,所以下一个数就是1211

1211 可以读成1个1,1个2,2个1,所以下一个数就是 111221

111221 可以读成3个1,2个2,1个1,所以下一个数就是 312211

从上述例子知道,下一个数就是上一个数的读法


解题报告:

从题目意思来看,我们需要定义这么几个变量

1、StringBuffer类型的res,用来作为字符串的缓冲区

2、String s 用来表示返回最后的字符串

3、int cnt ; 用来作为字符串缓冲区的临时字符串值

4、int round  迭代次数



完整代码:

该代码是来自http://blog.youkuaiyun.com/fightforyourdream/article/details/12901505 ,支持原创,我在原创代码的里添加了自己对代码理解的注释

package string;

public class S38{
	public static void main(String[] args){
		S38 s = new S38();
		System.out.println(s.countAndSay(6));		
	}
	public String countAndSay(int n){
		if(n == 1)
			return "1";
		
		//定义最后返回的字符串s
		String ss="1";
		
		//定义字符串缓冲区res
		StringBuffer res = new StringBuffer();
	
		//定义res里的元素cnt
		int cnt=0;
		//定义迭代次数round
		int round=0;
		int i;
		while(++round < n)
		{
			cnt = 1;
			res.setLength(0);//setLength()设置字符串的长度为0
			for(i=1;i<ss.length();i++){
				if(ss.charAt(i) == ss.charAt(i-1))//charAt :在字符序列ss中返回规定索引i对应的字符型取值
					cnt++;
				else{
					res.append(cnt).append(ss.charAt(i-1));//append:粘贴指定字符串到指定字符序列res中
					cnt=1;
				}
			}
			 res.append(cnt).append(ss.charAt(i-1));
			 ss=res.toString();//toString(): 返回字符串代表值
		}
		return res.toString();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值