当前位置:网站首页>394.字符串解码·栈
394.字符串解码·栈
2022-07-15 17:39:00 【小迅想变强】
链接:https://leetcode.cn/problems/decode-string/solution/c-by-xun-ge-v-oa5x/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目

示例

思路
题目需要进行对字符串子串进行对应数字扩展,需要用到栈思想
定义两个栈空间,这里用数组代替实现,数字存放在数字栈,字符串存放在字符串栈,遇到右括号时候,数字栈、字母栈弹到左括号为止。
具体实现
遍历字符串会遇见以下几种情况
1、当遇见'['时,入两个栈
2、当遇见数字时,入数字栈
3、当遇见字母时,入字母栈
4、当遇见']'时,将数字栈、字母栈元素弹出到左括号为止,然后将弹出的字符按数字栈中对应的数字进行扩展,然后又将扩展之后的字符压回字符栈,数字就丢了
代码
/*
*char * decodeString(char * s)
char * decodeString:对字符串子串进行对应数字扩展
char * s:字符串
返回值:扩展之后的字符串
*/
char * decodeString(char * s){
char * str1 = malloc(sizeof(char) * 9000);//数字栈
char * str2 = malloc(sizeof(char) * 9000);//字符栈
int len = strlen(s);
int i_1 = 0, i_2 = 0;
for(int i = 0; i < len; i++)//遍历整个字符串
{
if(s[i] == '[')//1、当遇见'['时,入两个栈
{
str1[i_1++] = '[';
str2[i_2++] = '[';
}
else if(s[i] == ']')//4、当遇见']'时
{
//计算一下数字栈的int类型值
int sum = 0;
int x = 10;
sum += (str1[i_1-2]-'0');
i_1 = i_1-2;
while(i_1 > 0 && str1[i_1-1] != '[')
{
sum += (str1[i_1-1]-'0') * x;
i_1--;
x *= 10;
}
//申请一个额外的空间临时保存一下弹出后的字符串
char buf[3000];
int mm = 3000;
i_2--;
while(str2[i_2] != '[')//先弹出
{
buf[--mm] = str2[i_2--];
}
while(sum--)//循环保存,扩展字符串
{
for(int m = mm; m < 3000; m++)
{
str2[i_2++] = buf[m];
}
}
}
else if(isalpha(s[i]) == 0)//2、当遇见数字时,入数字栈,isalpha检查输入字符是不是字母,返回值为0不是字符,不为0是字符
{
str1[i_1++] = s[i];
}
else//3、当遇见字母时,入字母栈
{
str2[i_2++] = s[i];
}
}
str2[i_2] = '\0';
return str2;
}
时间空间复杂度

边栏推荐
- Openharmony module 2 file samgr_ Server parsing (5)
- 汇编入门指南
- JVM tuning command encyclopedia and common command tools and practical steps
- 分库分表真的适合你的系统吗?聊聊分库分表和NewSQL如何选择
- C#小技巧 获取枚举所有枚举值
- openGauss 联合产业界创新,共建开源数据库根社区
- 秋招拿了6offer,总结了20多类1100道面试题含答案解析
- Openharmony module II parsing of header files under interfaces (9)
- AMD Ryzen 5 7600X 6核心和4.4GHz 'Zen 4 ' CPU现身跑分数据库
- 驳'一切不谈考核的管理都是扯淡'
猜你喜欢

Get to know the three modules of openharmony

Pytorch中torch.sort()和torch.argsort()函数解析

软件架构与设计(八)-----分布式架构

2、趋势科技2017校招开发岗试题

软件架构与设计(六)-----层次结构体

Qiu Zhao took 6 offers and summarized more than 20 categories of 1100 interview questions, including answer analysis

蓝领困顿,直播带岗是真伪需求?

AES encryption learning of openharmony security module

Use SSH to pull code

(高频面试题)计算机网络
随机推荐
Several things I want to understand about being laid off at the age of 30
模块二interfaces下头文件解析(2)
Amd ryzen 5 7600x 6 core and 4.4ghz'zen 4 'CPU appear in the running sub database
Pytorch中[:,None]的用法解析
二路归并排序总结
FrameWork源码——Binder 驱动解析
Procédure d'essai de pénétration
Can you use redis? Then come and learn about redis protocol
JVM调优命令大全及常用命令工具和实战步骤
在创建生成WIFI二维码手机扫码链接
CAS与AQS简单理解
How to greedy match in VIM
Calculate the distance between two points according to longitude and latitude
1. Huawei machine test question record
30岁被裁,我想明白的几件事
Pytorch中torch.full(),torch.ones()和torch.zeros()函数解析
Dataarts, a data governance production line, makes "everyone an analyst"
一家火锅店,凑了三个IPO
Query distance according to longitude and latitude and sort by distance
汇编入门指南