LeetCode //C - 38. Count and Say Medium Topics Companies

38. Count and Say

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

  • countAndSay(1) = “1”
  • countAndSay(n) is the way you would “say” the digit string from countAndSay(n-1), which is then converted into a different digit string.

To determine how you “say” a digit string, split it into the minimal number of substrings such that each substring contains exactly one unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.

For example, the saying and conversion for digit string “3322251”:
在这里插入图片描述
Given a positive integer n, return the n t h n^{th} nth term of the count-and-say sequence.
 

Example 1:

Input: n = 1
Output: “1”
Explanation: This is the base case.

Example 2:

Input: n = 4
Output: “1211”
Explanation:
countAndSay(1) = “1”
countAndSay(2) = say “1” = one 1 = “11”
countAndSay(3) = say “11” = two 1’s = “21”
countAndSay(4) = say “21” = one 2 + one 1 = “12” + “11” = “1211”

Constraints:
  • 1 <= n <= 30

From: LeetCode
Link: 38. Count and Say


Solution:

Ideas:
  1. Base Case: If n is 1, the function returns the string “1”, since the first term of the sequence is always “1”.
  2. Recursive Call: For n greater than 1, the function calls itself to calculate the (n-1)th term. This is because to say the nth term, you need to know the (n-1)th term first.
  3. Calculating the Length: It then calculates the length of the (n-1)th term to determine how much memory to allocate for the nth term. The allocation is generous to ensure there’s enough space since the length of the sequence can grow with each term. The malloc function is used to allocate the memory, and the sprintf function is used to convert the counts and digits into a string format.
  4. Building the nth Term: The function iterates through the digits of the (n-1)th term. For each group of the same digit, it counts how many times that digit appears consecutively (count). It then writes the count and the digit itself into the result string. The sprintf function returns the number of characters written (excluding the null terminator), which is used to update the result_index to know where to write the next characters.
  5. Ending the String: Once all groups of digits have been processed, a null terminator (‘\0’) is added to the end of the result string to properly terminate it.
  6. Memory Management: The function then frees the memory allocated for the (n-1)th term since it is no longer needed. This is important to prevent memory leaks.
  7. Return Result: Finally, the nth term, now stored in result, is returned to the caller. The caller, in this case, the main function, is responsible for freeing this memory after it’s done using it.
Code:
char* countAndSay(int n) {
    if(n == 1) return strdup("1");
    
    // Recursively call countAndSay to get the previous term
    char* prev_term = countAndSay(n - 1);
    int length = strlen(prev_term);
    
    // Calculate the maximum length of the result
    // In the worst case, the length doubles (e.g., "1" -> "11")
    char* result = malloc(2 * length + 1);
    int result_index = 0;

    for(int i = 0; i < length; i++) {
        int count = 1;
        // Count the number of identical digits
        while(i + 1 < length && prev_term[i] == prev_term[i + 1]) {
            count++;
            i++;
        }
        // Append count and digit to the result string
        result_index += sprintf(result + result_index, "%d%c", count, prev_term[i]);
    }

    // Free the memory allocated for previous term
    free(prev_term);

    // Add the null terminator to the result string
    result[result_index] = '\0';
    
    return result;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/571868.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

StrongSORT——基于DeepSORT,提高多目标跟踪的准确性和鲁棒性

1、概述 1.1 DeepSORT DeepSORT算法是在SORT基础上发展起来的一种多目标跟踪算法。SORT算法结合了目标检测器和跟踪器&#xff0c;其中跟踪器的核心是卡尔曼滤波和匈牙利算法。 卡尔曼滤波用于预测目标在下一帧的位置和状态而匈牙利算法则用于将预测状态与实际检测结果进行最…

Linksys RE7000 “AccessControlList ”命令执行漏洞(CVE-2024-25852 )

声明&#xff1a; 本文仅用于技术交流&#xff0c;请勿用于非法用途 由于传播、利用此文所提供的信息而造成的任何直接或者间接的后果及损失&#xff0c;均由使用者本人负责&#xff0c;文章作者不为此承担任何责任。 简介 Linksys RE7000 是由 Linksys 公司生产的一款 Wi-F…

Netty学习——实战篇5 Netty 心跳监测/WebSocket长连接编程 备份

1 心跳监测 MyServer.java public class MyServer {public static void main(String[] args) {NioEventLoopGroup bossGroup new NioEventLoopGroup(1);NioEventLoopGroup workerGroup new NioEventLoopGroup();try {ServerBootstrap serverBootstrap new ServerBootstrap…

DevOps文化对团队有何影响?

DevOps文化对团队有很多积极影响&#xff0c;包括提高团队效率、促进沟通与协作、提高产品质量和推动创新等方面。然而&#xff0c;实施DevOps文化也需要一定的挑战&#xff0c;如改变团队成员的观念、引入新的工具和流程等。因此&#xff0c;团队需要充分了解DevOps文化的价值…

【Ant-Desgin-React 穿梭框】表格穿梭框,树穿梭框的用法

Antd Desgin 穿梭框 普通用法高级用法-表格穿梭框组件高级用法-树穿梭框组件 普通用法 /* eslint-disable no-unused-vars */ import React, { useEffect, useState } from react import { Space, Transfer } from antd// Antd的穿梭框组件Mock数据 const mockData Array.fro…

CJSON工具类

4.4.3.CJSON工具类 OpenResty提供了一个cjson的模块用来处理JSON的序列化和反序列化。 官方地址&#xff1a; https://github.com/openresty/lua-cjson/ 1&#xff09;引入cjson模块&#xff1a; local cjson require "cjson"2&#xff09;序列化&#xff1a; …

记录海豚调度器删除工作流实例失败的解决办法(DolphinScheduler的WebUI删除失败)

本博客记录以下问题解决办法&#xff1a;使用dolphinscheduler的WebUI运行工作流后出现内存占用过高导致的任务阻塞问题&#xff0c;并且在删除工作流实例时总是报错无法删除 解决步骤 在前端页面无法删除&#xff0c;于是搜索资料&#xff0c;发现可以登录数据库进行工作流实…

Day05-docker-compose与私有仓库

Day05-docker-compose与私有仓库 3.4 Docker Compose1&#xff09;compose极速上手指南案例28-初步上手docker-compose2&#xff09;compose文件的常用指令3&#xff09;案例29-docker-compose部署kodexp5&#xff09;小结 3.5 docker镜像仓库之registry仓库1&#xff09;仓库选…

Qt中常用对话框

Qt中的对话框&#xff08;QDialog&#xff09;是用户交互的重要组件&#xff0c;用于向用户提供特定的信息、请求输入、或进行决策。Qt提供了多种标准对话框以及用于自定义对话框的类。以下将详细介绍几种常用对话框的基本使用、使用技巧以及注意事项&#xff0c;并附带C示例代…

SV-7041T IP网络有源音箱 教室广播多媒体音箱(带本地扩音功能)教学广播音箱 办公室背景音乐广播音箱 2.0声道壁挂式网络有源音箱

SV-7041T IP网络有源音箱 教室广播多媒体音箱&#xff08;带本地扩音功能&#xff09; 教学广播音箱 办公室背景音乐广播音箱 一、描述 SV-7041T是深圳锐科达电子有限公司的一款2.0声道壁挂式网络有源音箱&#xff0c;具有10/100M以太网接口&#xff0c;可将网络音源通过自带…

学习指导|在改变

备忘在这里啦。潦草本草

黑马微服务课程2

课程地址&#xff1a;2024最新SpringCloud微服务开发与实战&#xff0c;java黑马商城项目微服务实战开发&#xff08;涵盖MybatisPlus、Docker、MQ、ES、Redis高级等&#xff09;_哔哩哔哩_bilibili 课程名称&#xff1a;2024最新SpringCloud微服务开发与实战&#xff0c;java…

【1429】招生管理管理系统Myeclipse开发mysql数据库web结构java编程计算机网页项目

一、源码特点 java 招生管理系统是一套完善的java web信息管理系统&#xff0c;对理解JSP java编程开发语言有帮助&#xff0c;系统具有完整的源代码和数据库&#xff0c;系统主要采用B/S模式开发。开发环境为 TOMCAT7.0,Myeclipse8.5开发&#xff0c;数据库为Mysql5.0&…

android脱壳:一种使用native进行抽取壳脱壳的方法,native版本的frida-fart

前言 写rxposed的时候&#xff0c;搞了很多模块&#xff0c;其中有一个远程调用脱壳的&#xff0c;但是当时使用的是rmi远程调用&#xff0c;因为一些问题无法使用&#xff0c;可能是对抗问题&#xff0c;也有可能是技术问题&#xff0c;所以我又换了一种远程调用方式。 概述…

21-22 - 线性表的链式存储结构 单链表的具体实现

---- 整理自狄泰软件唐佐林老师课程 文章目录 1. 线性表的链式存储结构1.1 定义1.2 逻辑结构1.3 专业术语的统一 2. 链表的基本概念2.1 单链表中的结点定义2.2 单链表中的内部结构2.3 在目标位置处插入数据元素2.4 在目标位置处删除数据元素 3. 链式存储结构线性表的实现3.1 设…

排列对称串

Description:很多字串&#xff0c;有些是对称的&#xff0c;有些是不对称的&#xff0c;请将那些对称的字事按从小到大的顺序输出&#xff0c;字事先以长度论大小&#xff0c;如果长度相同&#xff0c;再以ASCI码值为大小标准 Input.输入数据中含有一些字串(1≤串长≤256)。 #…

linux文件句柄数满,linux文件句柄数超出系统限制怎么办?

1、问题阐述&#xff1a; too many open files&#xff1a;顾名思义即打开过多文件数。 不过这里的files不单是文件的意思&#xff0c;也包括打开的通讯链接(比如socket)&#xff0c;正在监听的端口等等&#xff0c;所以有时候也可以叫做句柄(handle)&#xff0c;这个错误通常…

Rust腐蚀服务器搭建架设教程ubuntu系统

Rust腐蚀服务器搭建架设教程ubuntu系统 大家好我是艾西一个做服务器租用的网络架构师。Rust腐蚀游戏对于服务器的配置有一定的要求很多小伙伴就思考用linux系统搭建的话占用会不会小一点&#xff0c;有一定电脑基础的小伙伴都知道Linux系统和windows系统相比较linux因为是面板…

coreldraw2024精简版绿色版安装包免费下载

CorelDRAW 2024是一款矢量图形设计软件&#xff0c;于2024年3月5日正式在全球范围内发布。这款软件在多个方面进行了更新和改进&#xff0c;为用户提供了更多高效、灵活和便捷的设计工具。 首先&#xff0c;CorelDRAW 2024新增了绘画笔刷功能&#xff0c;这些笔刷不仅模拟了传…

算法学习001-圆桌问题 中小学算法思维学习 信奥算法解析 c++实现

目录 算法学习001-圆桌问题 一、题目要求 1、编程实现 2、输入输出 二、算法分析 三、程序编写 四、程序说明 五、运行结果 六、考点分析 七、推荐资料 算法学习001-圆桌问题 一、题目要求 1、编程实现 圆桌边围坐着2n个人&#xff0c;其中n个人是好人&#xff0c…
最新文章