394. 字符串解码

394. 字符串解码

  1. class Solution:
  2.     def decodeString(self, s: str) -> str:
  3.         stack=[]
  4.         res=""
  5.         multi=0
  6.         for i in s:
  7.             if i =='[':
  8.                 stack.append([multi,res])
  9.                 res,multi="",0
  10.             elif i==']':
  11.                 cur_multi,cur_res=stack.pop()
  12.                 res=cur_res+cur_multi*res
  13.             elif '0'<=i<='9':
  14.                 multi=multi*10+int(i)
  15.             else:
  16.                 res+=i
  17.         return res
       看似简单实则不然
ai注释版:

class Solution:
def decodeString(self, s: str) -> str:
# 初始化变量
stack = [] # 用于存储[次数,之前的字符串]
res = "" # 当前构建的结果字符串
multi = 0 # 当前的数字(重复次数)

# 遍历字符串的每个字符
for i in s:
if i == '[':
# 遇到左括号,保存当前的倍数和之前的结果
stack.append([multi, res])
# 重置当前结果和倍数
res, multi = "", 0
elif i == ']':
# 遇到右括号,取出之前保存的倍数和字符串
cur_multi, cur_res = stack.pop()
# 组合新的结果:之前的字符串 + 当前字符串重复指定次数
res = cur_res + cur_multi * res
elif '0' <= i <= '9':
# 处理数字,构建多位数字
multi = multi * 10 + int(i)
else:
# 处理字母,直接添加到结果中
res += i
return res

 

 

multi = multi * 10 + int(i)详细解释:

这行代码的工作原理:

  1. multi * 10:将已有的数字左移一位(相当于乘以10)
  1. int(i):将当前字符转换为数字
  1. 两者相加:将新数字添加到正确的位置
这样就能正确处理任意位数的数字,比如:

  • "1" → 1
  • "12" → 12
  • "123" → 123
  • "1234" → 1234
这种方法是处理多位数字的标准做法,类似于我们手动计算数字的过程。

发表评论