LeetCode每日一题(Decode String)

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

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

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)
    }
}
### LeetCode Top 100 经典编程题目 LeetCode 上有许多经典的编程挑战,这些题目被广泛认为是掌握算法和数据结构的关键[^1]。以下是精选的一部分Top 100经典问题列表: #### 数组与字符串 1. **Two Sum** 2. **Add Two Numbers** 3. **Longest Substring Without Repeating Characters** #### 动态规划 4. **Climbing Stairs** 5. **Best Time to Buy and Sell Stock II** 6. **Unique Paths** #### 链表操作 7. **Merge Two Sorted Lists** 8. **Remove Nth Node From End of List** 9. **Reverse Linked List** #### 栈与队列 10. **Valid Parentheses** 11. **Min Stack** 12. **Implement Queue using Stacks** #### 排序与搜索 13. **Search Insert Position** 14. **Find First and Last Position of Element in Sorted Array** 15. **Sort Colors** #### 图论基础 16. **Clone Graph** 17. **Pacific Atlantic Water Flow** 18. **Number of Islands** #### 字符串处理 19. **String to Integer (atoi)** 20. **Valid Number** 21. **Decode Ways** #### 贪心算法 22. **Jump Game** 23. **Gas Station** 24. **Task Scheduler** 以上仅展示了部分LeetCode上被认为是经典的问题。对于完整的Top 100列表,建议访问官方推荐页面获取最新更新的信息。 ```python # 示例代码:验证括号的有效性 def isValid(s: str) -> bool: stack = [] mapping = {")": "(", "}": "{", "]": "["} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping.keys(): if not stack or stack.pop() != mapping[char]: return False return len(stack) == 0 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值