0
点赞
收藏
分享

微信扫一扫

394. 字符串解码-739. 每日温度

394. 字符串解码

给定一个经过编码的字符串,返回它解码后的字符串。

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

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

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

 

示例 1:

输入:s = "3[a]2[bc]"
输出:"aaabcbc"

示例 2:

输入:s = "3[a2[c]]"
输出:"accaccacc"

示例 3:

输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"

示例 4:

输入:s = "abc3[cd]xyz"
输出:"abccdcdcdxyz"

 

提示:

  • 1 <= s.length <= 30
  • s 由小写英文字母、数字和方括号 '[]' 组成
  • s 保证是一个 有效 的输入。
  • s 中所有整数的取值范围为 [1, 300] 


class Solution {
public:
    string decodeString(string s) {
        stack<string> st;   // 用于保存中间结果的栈
        stack<int> rep;     // 用于保存重复次数的栈
        string currentStr = "";  // 当前正在构建的字符串
        int currentNum = 0;      // 当前的数字

        for (char c : s) {
            if (isdigit(c)) {
                // 累积当前数字
                currentNum = currentNum * 10 + (c - '0');
            } else if (c == '[') {
                // 遇到 '[',将当前字符串和数字压入栈,并重置状态
                st.push(currentStr);
                rep.push(currentNum);
                currentStr = "";  // 重置当前字符串
                currentNum = 0;   // 重置数字
            } else if (c == ']') {
                // 遇到 ']',弹栈并重复拼接字符串
                string temp = currentStr;
                int repeat = rep.top(); rep.pop();
                currentStr = st.top(); st.pop();
                // 使用循环构造一次性拼接
                for (int i = 0; i < repeat; i++) {
                    currentStr += temp;
                }
            } else {
                // 普通字符,直接加入当前字符串
                currentStr += c;
            }
        }

        return currentStr;
    }
};

739. 每日温度

给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,请在该位置用 0 来代替。

 

示例 1:

temperatures

示例 2:

输入: temperatures = [30,40,50,60]
输出: [1,1,1,0]

示例 3:

输入: temperatures = [30,60,90]
输出: [1,1,0]

 

提示:

  • 1 <= temperatures.length <= 105
  • 30 <= temperatures[i] <= 100


class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        int n=temperatures.length;
        int[] res = new int[n];
        res[n-1] = 0;
        for(int i=n-2; i>=0; i--){
            if(temperatures[i+1]>temperatures[i]){
                res[i] = 1;
            }else{
                int add = res[i+1];
                int sum = i+1;
                while(add != 0){                    
                    sum += add;
                    add = res[sum];
                    if(temperatures[sum]>temperatures[i]){
                        res[i] = sum - i;
                        break;
                    }
                }
                
            }
        }
        return res;
    }
}







举报

相关推荐

0 条评论