LeetCode hot100-71

https://leetcode.cn/problems/decode-string/description/?envType=study-plan-v2&envId=top-100-liked

394. 字符串解码
已解答
中等
相关标签
相关企业
给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

这个解法逻辑清晰一点,但是也不好想。拿一个输入跟着逻辑走一遍大概能理解

class Solution {
    public String decodeString(String s) {
        Stack<Integer> countStack = new Stack<Integer>();
        Stack<String> stringStack = new Stack<String>();
        int num = 0;
        // res是不断解码中间过程也保存在这个变量
        String res = "";
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if ('0' <= ch && ch <= '9') {
                // 计算重复的次数,如果数字是大于9的情况。就不止一位数
                num = num * 10 + (ch - '0');
            } else if (ch == '[') {
                countStack.push(num);
                stringStack.push(res);
                num = 0;
                res = "";
            } else if (ch == ']') {
                int repeat = countStack.pop();
                // 目前栈中的字符串。比如这个输入3[a]2[bc]。目前栈中的字符串为aaa,res为bc
                String now = stringStack.pop();
                for (int j = 0; j < repeat; j++) {
                    now = now + res;
                }
                res = now;
            } else {
                res = res + ch;
            }
        }
        return res;
    }
}
### 关于 LeetCode Hot100 的题目解析与代码实现 以下是针对部分经典 LeetCode Hot100 题目的详细解析和代码实现: --- #### **可被三整除的最大和** 此题的核心在于动态规划的应用。通过构建状态转移方程来解决子序列求和问题。 ```python from functools import lru_cache def maxSumDivThree(nums): @lru_cache(None) def dp(index, remainder): if index == len(nums): return 0 if remainder == 0 else float('-inf') take = nums[index] + dp(index + 1, (remainder + nums[index]) % 3) not_take = dp(index + 1, remainder) return max(take, not_take) return dp(0, 0) ``` 上述方法利用记忆化递归来优化时间复杂度,确保每种可能的状态仅计算一次[^1]。 --- #### **玩筹码** 该问题可以通过贪心算法高效解决。核心思路是统计奇偶位置上的筹码数量并选择代价较小的操作方式。 ```python def minCostToMoveChips(position): even_count = sum(p % 2 == 0 for p in position) odd_count = len(position) - even_count return min(even_count, odd_count) ``` 这里的时间复杂度为 O(n),其中 n 是 `position` 数组的长度。 --- #### **买卖股票的最佳时机** 这是一道经典的单次交易最大利润问题,可以采用线性扫描的方式完成。 ```python def maxProfit(prices): min_price = float('inf') max_profit = 0 for price in prices: if price < min_price: min_price = price elif price - min_price > max_profit: max_profit = price - min_price return max_profit ``` 这段代码的关键在于维护当前最低价格以及潜在的最大收益。 --- #### **跳跃游戏 I 和 II** 这两道题分别涉及布尔判断和最小步数计算。前者可通过记录可达范围快速判定,后者则需借助动态规划思想逐步推进最优路径。 ##### 跳跃游戏 I ```python def canJump(nums): farthest = 0 for i, jump in enumerate(nums): if i > farthest: return False farthest = max(farthest, i + jump) return True ``` ##### 跳跃游戏 II ```python def jump(nums): jumps = current_end = farthest = 0 for i in range(len(nums) - 1): farthest = max(farthest, i + nums[i]) if i == current_end and i != len(nums) - 1: jumps += 1 current_end = farthest return jumps ``` 两者的共同特点是基于局部最优解推导全局最佳策略。 --- #### **划分字母区间** 本题要求找到字符串中的不重叠分区数目,适合用双指针配合哈希表处理。 ```python def partitionLabels(s): last_occurrence = {c: i for i, c in enumerate(s)} partitions = [] start = end = 0 for i, char in enumerate(s): end = max(end, last_occurrence[char]) if i == end: partitions.append(end - start + 1) start = i + 1 return partitions ``` 这种方法能够在线性时间内解决问题,并且保持空间开销较低。 --- #### **移动零** 对于数组操作类问题,“头部”扩展技巧非常实用。具体做法如下所示: ```python def moveZeroes(nums): head = 0 for i in range(len(nums)): if nums[i] != 0: nums[head], nums[i] = nums[i], nums[head] head += 1 ``` 此处逻辑清晰明了,只需两次遍历即可达成目标[^2]。 --- ### 总结 以上展示了若干热门 LeetCode 题目及其解决方案。这些例子涵盖了多种常见算法模式,包括但不限于动态规划、贪心算法、滑动窗口等技术手段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值