2021-03-22极客时间打卡

16.26. 计算器 https://leetcode-cn.com/problems/calculator-lcci/

给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。

表达式仅包含非负整数,+, - ,*,/ 四种运算符和空格 。 整数除法仅保留整数部分。

输入: "3+2*2"
输出: 7

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        char opt = '+';
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (Character.isDigit(ch))
                num = num * 10 + (ch - '0');
            if ((!Character.isDigit(ch) && ch != ' ') || i == s.length() - 1) {

                if (opt == '+')
                    stack.push(num);
                else if (opt == '-')
                    stack.push(-num);
                else if (opt == '*')
                    stack.push(stack.pop() * num);
                else
                    stack.push(stack.pop() / num);

                num = 0;
                opt = ch;
            }
        }
        int result = 0;
        while (!stack.isEmpty())
            result += stack.pop();
        return result;
    }
}

739. 每日温度 https://leetcode-cn.com/problems/daily-temperatures/

请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 0 来代替。

例如,给定一个列表 temperatures = [73, 74, 75, 71, 69, 72, 76, 73],你的输出应该是 [1, 1, 4, 2, 1, 1, 0, 0]。

提示:气温 列表长度的范围是 [1, 30000]。每个气温的值的均为华氏度,都是在 [30, 100] 范围内的整数。

class Solution {
    public int[] dailyTemperatures(int[] T) {
        int[] res = new int[T.length];
        for(int i=T.length - 2;i>=0;i--){
            for(int j=i+1;j<T.length;j+=res[j]){
                if(T[j] > T[i]){
                    res[i] = j-i;
                    break;
                }else if(res[j] == 0){
                    res[i] = 0;
                    break;
                }
            }
        }
        return res;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、面试题 01.03. URL化:https://leetcode-cn.com/problems/string...
    程博颖阅读 225评论 0 0
  • 请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这...
    快乐的老周阅读 257评论 0 0
  • 根据每日 气温 列表,请重新生成一个列表,对应位置的输出是需要再等待多久温度才会升高超过该日的天数。如果之后都不会...
    放下梧菲阅读 190评论 0 0
  • 栈 有效的括号[https://leetcode-cn.com/problems/valid-parenthese...
    dawsonenjoy阅读 389评论 0 0
  • 数组 合并两个有序数组[https://leetcode-cn.com/problems/merge-sorted...
    思源堂阅读 193评论 0 0