Count and Say

本文介绍了一个生成计数并描述序列的算法实现。通过递归的方式,该算法能够生成任意阶数的计数并描述序列。文章提供了完整的Java代码示例,并展示了从n=1到n=6的序列生成结果。
 1 public class Solution {
 2    public String countAndSay(int n) {
 3     String res = "1";
 4     if(n==0)  return res;
 5     for(int i=1;i<n;i++){
 6         res =get(res);
 7     }
 8     return res;
 9     }
10     
11     public String get(String res){
12         int count = 1;
13         char last=' ';
14         String temp ="";
15         for(int i=0;i<res.length();i++){
16             if(i<res.length()-1 && res.charAt(i)==res.charAt(i+1)){
17                 count++;
18                 last = res.charAt(i+1);
19             }
20             else{
21                 if(count>1){
22                     temp = temp+count+last;
23                     count = 1;
24                 }
25                 else{
26                     temp = temp+count+res.charAt(i);
27                 }
28             }
29         }
30         return temp;
31     }
32 }
View Code

n=1: 1

n=2:1 1

n=3: 2 1

n=4: 1211

n=5:111221

n=6:312211

转载于:https://www.cnblogs.com/krunning/p/3545275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值