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

news2024/10/5 12:43:37

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.coloradmin.cn/o/1625468.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【C语言】万字详讲操作符

目录 前言 一、操作符分类 二、算数操作符 三、移位操作符 四、位操作符 五、赋值操作符 六、单目操作符 6.1 逻辑反操作 6.2 负值与正值 6.3 取地址 6.4 sizeof 6.5 取反操作符 6.6 --和操作符 6.7 间接访问操作符&#xff08;解引用操作符&#xff09; 6.8 强…

比较好的平民衣服品牌有哪些?平价质量好短袖品牌推荐

随着气候变暖&#xff0c;夏天的持续时间似乎越来越长&#xff0c;短袖作为夏季的必备服装&#xff0c;受到了广大男士的青睐。然而&#xff0c;面对市场上众多的短袖品牌和不同的质量&#xff0c;大家都觉得选短袖的时候实在难以找到质量好且合适自己的。 选择合适的短袖确实…

中级信息系统管理工程师-必会题锦集

文章目录 中级信息系统管理工程师-必会题锦集题目一CPU[解析]试题二 CPU[解析] 中级信息系统管理工程师-必会题锦集 题目一CPU CPU中&#xff08;1&#xff09;不仅要保证指令的正确执行&#xff0c;还要能够处理异常事件。 A. 运算器 B. 控制器 C. 寄存器组 D. 内部总线 [解…

Elasticsearch单机部署(Linux)

1. 准备环境 本文中Elasticsearch版本为7.12.0&#xff0c;JDK版本为1.8.0&#xff0c;Linux环境部署。 扩展&#xff1a; &#xff08;1&#xff09;查看Elasticsearch对应的常用的jdk版本如下&#xff1a;&#xff08;详情可看官网的支持一览表&#xff09; Elasticsearch a…

牛客NC221 集合的所有子集(二)【中等 深度优先,子集,排列组合 C++/Java/Go/PHP】

题目 题目链接&#xff1a; https://www.nowcoder.com/practice/a3dfd4bc8ae74fad9bc65d5ced7ae813 核心 和n数之和的问题 差不多&#xff0c;都是需要找到数字的排列组合参考答案C class Solution {public:/*** 代码中的类名、方法名、参数名已经指定&#xff0c;请勿修改&a…

获取boss直聘城市地区josn数据

获取boss直聘城市地区josn数据 当我需要爬取多个城市的地区的时候&#xff0c;只能手动点击&#xff0c;然后一个一个看 结果&#xff1a; 能看到所有区域所有子地区的地区代码 解析该JSON数据 import pandas as pd import requests code[] area[] 城市代码101210100 res…

ScriptableObject数据容器讲解

概述 是Unity提供的一个用于创建可重用的数据容器或逻辑的基类。 ScriptableObject 是继承自 UnityEngine.Object 的一个类&#xff0c;但与普通的 MonoBehaviour 不同&#xff0c;它不能附加到GameObject上作为组件。 相反&#xff0c;ScriptableObject 通常用于存储和管理…

飞鹤与满趣健达成战略合作 加速深化国际化布局

继获得加拿大地区首张婴幼儿配方奶粉生产执照后&#xff0c;中国飞鹤的海外征途再添新动作。4月25日&#xff0c;中国飞鹤加拿大皇家妙克与美国婴童用品巨头满趣健&#xff08;Munchkin&#xff09;在北京正式达成战略合作。此次合作彰显了中国乳企的硬核实力&#xff0c;也是飞…

java:Http协议和Tomcat

HTTP协议 Hyper Text Transfer Protocol 超文本传输协议,规定了浏览器和服务器之间数据传输的规则 特点: 基于TCP协议,面向连接,安全 基于请求响应模型:一次请求对应一次响应 HTTP协议是无状态协议,对事务的处理没有记忆能力,每次请求-响应都是独立的. 优点 速度较快 …

Win11和WinRAR取消折叠菜单恢复经典菜单

这里写目录标题 前言1. Win11恢复经典右键菜单1.1 修改前1.2 恢复成经典右键菜单1.3 修改后1.4 想恢复怎么办&#xff1f; 2. WinRAR取消折叠菜单恢复经典菜单2.1 修改前2.2 修改恢复为经典菜单2.3 修改后2.4 想恢复怎么办&#xff1f; 前言 最近换回了Windows电脑&#xff0c…

网络攻击近在咫尺:数据加密与SSL成为信息安全之盾

随着互联网的日益普及和科技的迅猛发展&#xff0c;网络攻击已经成为信息安全领域面临的一大难题。近期&#xff0c;一场网络安全实验让我们对网络攻击有了更为深刻的认识。在实验中&#xff0c;网络安全工程师通过模拟攻击&#xff0c;展示了木马植入、文件浏览、键盘监听、病…

618大促有哪些值得买的家居好物?618五款必Buy好物

来了&#xff01;来了&#xff01;万众瞩目的618购物狂欢节即将拉开帷幕&#xff0c;我们的目标清晰而坚定&#xff0c;那就是用最实惠的价格尽情享受购物的乐趣。然而&#xff0c;面对各种纷繁复杂的促销活动和琳琅满目的商品&#xff0c;选择困难症似乎也在悄然滋生。因此&am…

安全AI未来 | C3安全大会 · 2024,数据驱动 AI原生

数字为时代变革注入动力&#xff0c;AI为重塑社会文明带来原力。数智浪潮中&#xff0c;我们见证着时代跃迁的巨变&#xff0c;面临着适变、应变、驭变的挑战。 数字驱动、AI原生。数字的流动不仅承载着信息&#xff0c;更将激活未来的无限价值&#xff1b;AI&#xff0c;不…

FastAPI从入门到实战(16)——请求参数汇总

FastAPI有各种各样的参数,包括: url参数(定义在url中的参数)param参数(使用url后面?xxxx)定义的参数body参数(在请求主体中携带的json参数)form参数(在请求主体中携带的web表单参数)cookie参数(在请求的cookie中携带的参数)file参数(客户端上传的文件) 1. url参数 from fas…

金属冶炼及压延加工制造数字孪生可视化平台,推进行业数字化转型

金属冶炼及压延加工制造数字孪生可视化平台&#xff0c;推进行业数字化转型。随着科技的不断进步和工业的快速发展&#xff0c;金属冶炼及压延加工行业正面临着前所未有的挑战和机遇&#xff0c;数字化转型成为了行业发展的必然趋势。在这个过程中&#xff0c;数字孪生可视化平…

ArcGIS专题图制作—3D峡谷地形

6分钟教你在ArcGIS Pro中优雅完成炫酷的美国大峡谷3D地图 6分钟教你在ArcGIS Pro中优雅完成炫酷的美国大峡谷3D地图。 这一期的制图教程将带我们走入美国大峡谷&#xff0c;让我们一起绘制这张美妙的地图吧&#xff01;视频也上传到了B站&#xff0c;小伙伴可以去&#xff01; …

【项目亮点】大厂中分布式事务的最佳实践 问题产生->难点与权衡(偏爱Saga)->解决方案

【项目亮点】大厂中分布式事务的最佳实践 问题产生->难点与权衡->解决方案->底层实现->应用案例 不断有同学问我大厂中实践分布式事务的问题,这里从分布式事务的产生,到强弱一致性与性能的权衡,再到最终落地的解决方案,再到实际的代码实现,再到我工作中实际使用SA…

数据结构篇其一---顺序表

前言 数据结构篇&#xff0d;&#xff0d;&#xff0d;C语言实现数据结构 &#xff23;语言的基础知识&#xff1a;数组 函数 结构体 指针 动态内存分配。 顺序表 从数据结构的角度看待数组 int arr[10]; 数组是一个基本的数据结构吗&#xff1f; 这里以一维数组为例。 …

信号捕捉、可重入函数、volatile、SIGCHLD

个人主页&#xff1a;Lei宝啊 愿所有美好如期而遇 信号捕捉 signal 这个函数我们前面关于信号的文章多次提及&#xff0c;这里重点介绍sigaction。 sigaction 只需要看红色框住的属性即可&#xff0c;其余属性我们不使用&#xff0c;不用多管。第一个handler和signal的第二…

Vim学习笔记01~04

第01章&#xff1a; 遁入空门&#xff0c;模式当道 1.什么是vim Vim是一个高效的文本编辑工具&#xff0c;并且可以在编程开发过程中发挥越来越重要的作用。 事实上&#xff0c;有不少编程高手使用他们来进行代码的开发&#xff0c;并且对此赞不绝口。 2.本系列目的 但是让…