LeetCode每日一题(Decode String)

本文介绍如何解码给定的编码字符串,遵循k[encoded_string]的规则,其中encoded_string重复k次。文章通过举例说明解码过程,并提供了一个Rust语言的代码实现来解决这个问题。

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].

Example 1:

Input: s = “3[a]2[bc]”
Output: “aaabcbc”

Example 2:

Input: s = “3[a2[c]]”
Output: “accaccacc”

Example 3:

Input: s = “2[abc]3[cd]ef”
Output: “abcabccdcdcdef”

Example 4:

Input: s = “abc3[cd]xyz”
Output: “abccdcdcdxyz”

Constraints:

  • 1 <= s.length <= 30
  • s consists of lowercase English letters, digits, and square brackets ‘[]’.
  • s is guaranteed to be a valid input.
  • All the integers in s are in the range [1, 300].

每次读取一个字符, 根据字符的类型不同,有以下几种状态:

  • 数字: push 到 times_str, 留作后面转换成 times 来用
  • ‘[’: 递归调用,拿到下层的返回字符串,然后解析 times_str 得到 times, repeat 返回的字符串 times 次,然后推入 ans
  • ‘]’: 直接返回 ans
  • 其他: push 到 ans 中

代码实现(Rust):

impl Solution {
    fn decode(s: &mut String) -> String {
        let mut ans = String::new();
        let mut times_str = String::new();
        while !s.is_empty() {
            let c = s.remove(0);
            if c.is_numeric() {
                times_str.push(c);
            } else if c == '[' {
                let next = Solution::decode(s);
                let times = times_str.parse::<usize>().unwrap();
                ans.push_str(&next.repeat(times));
                times_str.clear();
            } else if c == ']' {
                return ans;
            } else {
                ans.push(c);
            }
        }
        ans
    }
    pub fn decode_string(mut s: String) -> String {
        Solution::decode(&mut s)
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值