当前位置: 首页 > news >正文

LeetCode - 394. 字符串解码

题目

394. 字符串解码 - 力扣(LeetCode)

思路

使用两个栈:一个存储重复次数,一个存储字符串

遍历输入字符串:

  • 数字处理:遇到数字时,累积计算重复次数
  • 左括号处理:保存当前状态(入栈),开始处理新的嵌套部分
  • 字母处理:直接添加到当前字符串,不涉及栈操作
  • 右括号处理:完成当前嵌套部分,应用重复规则,恢复之前的状态(出栈)

最终返回处理后的字符串

该算法能够处理嵌套的编码,例如"2[a2[bc]]"这样的情况。时间复杂度为O(n),其中n是输入字符串的长度。

过程

  • countStack: []
  • strStack: []
  • currentStr: ""
  • count: 0

处理字符 '3'

字符: '3'
操作: 数字 → 更新count = 3
countStack: []
strStack: []
currentStr: ""
count: 3

处理字符 '['

字符: '['
操作: 左括号 → 保存当前状态,重置当前变量
countStack: [3]  ← 入栈
strStack: [""]   ← 入栈
currentStr: ""   ← 重置
count: 0         ← 重置

 处理字符 'a'

字符: 'a'
操作: 字母 → 添加到currentStr
countStack: [3]
strStack: [""]
currentStr: "a"  ← 添加'a'
count: 0

处理字符 ']'

字符: ']'
操作: 右括号 → 出栈并应用重复
countStack: []   ← 弹出3
strStack: []     ← 弹出""
重复计算: "" + "a"*3 = "aaa"
currentStr: "aaa"  ← 更新
count: 0

 处理字符 '2'

字符: '2'
操作: 数字 → 更新count = 2
countStack: []
strStack: []
currentStr: "aaa"
count: 2         ← 更新

  处理字符 '['

字符: '['
操作: 左括号 → 保存当前状态,重置当前变量
countStack: [2]      ← 入栈
strStack: ["aaa"]    ← 入栈
currentStr: ""       ← 重置
count: 0             ← 重置

 处理字符 'b'

字符: 'b'
操作: 字母 → 添加到currentStr
countStack: [2]
strStack: ["aaa"]
currentStr: "b"      ← 添加'b'
count: 0

 处理字符 'c'

字符: 'c'
操作: 字母 → 添加到currentStr
countStack: [2]
strStack: ["aaa"]
currentStr: "bc"     ← 添加'c'
count: 0

 处理字符 ']'

字符: ']'
操作: 右括号 → 出栈并应用重复
countStack: []       ← 弹出2
strStack: []         ← 弹出"aaa"
重复计算: "aaa" + "bc"*2 = "aaa" + "bcbc" = "aaabcbc"
currentStr: "aaabcbc"  ← 更新
count: 0

  处理结束

最终结果: "aaabcbc"

一些难点解读

正确写法

class Solution {
public:string decodeString(string s) {stack<int> countStack;stack<string> strStack; string currentStr = "";int count = 0;for(int i = 0; i<s.size();i++){if(isdigit(s[i])){count = count * 10 + (s[i] - '0');}else if(s[i] == '['){countStack.push(count);strStack.push(currentStr);count = 0;currentStr = "";}else if(s[i] == ']'){int repeatTimes = countStack.top();countStack.pop();string decodedStr = strStack.top();strStack.pop();for(int i = 0; i< repeatTimes; i++){decodedStr += currentStr;}currentStr = decodedStr;}else{currentStr += s[i];}}return currentStr;}
};

相关文章:

  • Java多线程实现之Callable接口深度解析
  • 蓝桥杯 2024 15届国赛 A组 儿童节快乐
  • 清新文艺手绘学习教育培训竞标汇报PPT模版分享
  • error: Sandbox: rsync(17136) deny(1) file-write-create
  • 【论文解读】ReSearch:让LLM自主学习搜索
  • C++ 手写实现 unordered_map 和 unordered_set:深入解析与源码实战
  • C# 中常用的 字符串截取方法
  • ASP4644电源芯片FB引脚:从原理到实战
  • 电动汽车VCU扭矩控制模式分类方法
  • 软考 系统架构设计师系列知识点之杂项集萃(86)
  • MODERNTCN:一种面向通用时间序列分析的现代纯卷积结构
  • Web应用安全漏洞扫描:原理、常用方法及潜在风险解析?
  • 挑战杯推荐项目
  • 观成科技:隐蔽隧道工具Ligolo-ng加密流量分析
  • LarkXR 赋能AI x XR数字供应链:引领智能设计、数字孪生与零售新未来
  • 在centos 8上编译安装php8.0
  • 树莓派超全系列教程文档--(62)使用rpicam-app通过网络流式传输视频
  • TikTok矩阵养号实战:住宅IP纯净度与设备指纹联动方案
  • ubuntu搭建nfs服务centos挂载访问
  • 使用Spring Boot Actuator构建用户应用
  • wordpress自动发布图片/天津seo推广
  • 影视公司网站设计/全国最好网络优化公司
  • 如何做网站充值/重庆百度seo整站优化
  • 无锡做网站公司哪家比较好/推广平台排行榜
  • 威客网站系统/企业网络宣传推广方案
  • 海外营销网站设计/国家市场监管总局