38. Count and Say

题目描述(简单难度)

在这里插入图片描述
示例如下:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

初始值第一行是 1。

第二行读第一行,1 个 1,去掉个字,所以第二行就是 11。

第三行读第二行,2 个 1,去掉个字,所以第三行就是 21。

第四行读第三行,1 个 2,1 个 1,去掉所有个字,所以第四行就是 1211。

第五行读第四行,1 个 1,1 个 2,2 个 1,去掉所有个字,所以第五航就是 111221。

第六行读第五行,3 个 1,2 个 2,1 个 1,去掉所以个字,所以第六行就是 312211。

然后题目要求输入 1 - 30 的任意行数,输出该行是啥。

解法

两两字符之间依次进行对比,如果相邻字符相等,那么count+1;否则把后面字符赋值给前面字符,重复之前的操作。

Java

public String countAndSay(int n) {
        String pre ="1";
        for(int i = 1;i < n;i++){
            char first = pre.charAt(0);
            StringBuilder temp = new StringBuilder();
            int count = 1;
            for(int j = 1;j<pre.length();j++){
                char second = pre.charAt(j);
                if(first == second){
                    count++;
                }else{
                    temp.append(count).append(first);
                    count = 1;
                    first = second;
                }
            }
            temp.append(count).append(first);
            pre=temp.toString();
        }
        return pre;
    }
   public static void main(String args[]) {
	   int n=5;
	   String ans=countAndSay(n);
	   System.out.println(ans);
   }
}

在这里插入图片描述

Python

class Solution(object):
    def countAndSay(self, n):
        pre ="1"
        for i in range(1,n):
            first = pre[0]
            temp = []
            count = 1
            for j in range(1,len(pre)):
                second = pre[j]
                if first == second:
                    count+=1
                else:
                    temp.append(count)
                    temp.append(first)
                    count = 1
                    first = second

            temp.append(count)
            temp.append(first)
            new_temp = [str(x) for x in temp]
            pre="".join(new_temp)

        return pre    

在这里插入图片描述

参考文献

  • https://blog.csdn.net/google19890102/article/details/80932546
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安替-AnTi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值