算法题:字符串解码

本文介绍了如何解码带有#和%符号的字符串。通过利用栈数据结构,当遇到%时,按照栈中#前的数字重复输出相应字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一,问题描述

1,  给定一个字符串,目标是将写在#%之间的字符串,重复#号前面的数字次数(数字只会是个位数),

2,例如: 输入结果: strs = "he3#llo%world

                 输出结果: res = "hellollolloworld"

        输入结果:strs = "he3#ll2#o%wo%rld"

                 输出结果: res = "helloowolloowollooworld"

3, 算法思想:  利用一个栈数据结构,用来存放"#"对应的索引下标,在遍历字符串中,若遇到"%",则将栈中的元素退出来,进行匹配操作。

二, 程序:

1, 程序

class Solution(object):

    def __init__(self):

        # 主要存放"#"字符对应的下标
        self.stack = []

    def makestrs(self, strs):

        if strs == "" or len(strs) == 0:
            return strs

        data = 0
        i = 0
        
        # 遍历字符串
        while i < len(strs):
            # 碰到"#"字符,就将索引值存入stack中
            if strs[i] == "#" and i != 0:
                self.stack.append(i)

            # 碰到"%"字符, 就从stack中推出元素
            elif strs[i] == "%" and i != 0:
                left = self.stack.pop()
                right = i
                if left != 0:
                    if strs[left -1].isdigit():
                        data = int(strs[left-1])

                temp = data * strs[left+1:right]
                strs = strs[0:left-1] + temp + strs[right+1:]

                i = len(strs[0:left-1] + temp)

            i = i + 1

        if len(self.stack) > 0:
            return None
        else:
            return strs



if __name__ == "__main__":

    solution = Solution()
    # strs = "he3#llo%world"
    strs = "he3#ll2#o%wo%rld"

    res = solution.makestrs(strs)

    print("res = %s" % res)

 

       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值