leetCode第1989题
题目描述:
给定一个包含正整数、加(+)、减(-)、乘()、除(/)的算数表达式(括号除外),计算其结果。
表达式仅包含非负整数,+, - ,,/ 四种运算符和空格 。 整数除法仅保留整数部分。
class Solution {
public int calculate(String s) {
Stack<Integer> numStack = new Stack<>();
int num = 0;
char operator = '+';
for (int i = 0; i < s.length(); i++) {
char sym = s.charAt(i);
if (Character.isDigit(sym)) {
num = num * 10 + (sym - '0');
}
if ((s.charAt(i) != ' ' && !Character.isDigit(s.charAt(i))) || i == s.length()-1) {
if (operator == '+') {
numStack.push(num);
} else if (operator == '-') {
numStack.push(-num);
} else if (operator == '*') {
numStack.push(num * numStack.pop());
} else if (operator == '/') {
numStack.push(numStack.pop() / num);
}
operator = sym;
num = 0;
}
}
int result = 0;
while (!numStack.isEmpty()) {
result += numStack.pop();
}
return result;
}
}
leetcode第739题
题目描述:
请根据每日 气温 列表,重新生成一个列表。对应位置的输出为:要想观测到更高的气温,至少需要等待的天数。如果气温在这之后都不会升高,请在该位置用 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[] array = new int[T.length];
Stack<DaliyTmp> stack = new Stack<>();
for (int i = 0; i < T.length; i++) {
if (stack.isEmpty() || T[i] <= stack.peek().getVal()) {
DaliyTmp daliyTmp = new DaliyTmp();
daliyTmp.setIndex(i);
daliyTmp.setVal(T[i]);
stack.push(daliyTmp);
} else {
while (!stack.isEmpty() && T[i] >stack.peek().getVal()) {
array[stack.peek().getIndex()] = i - stack.pop().getIndex();
}
DaliyTmp daliyTmp = new DaliyTmp();
daliyTmp.setIndex(i);
daliyTmp.setVal(T[i]);
stack.push(daliyTmp);
}
}
while (!stack.isEmpty()) {
array[stack.pop().getIndex()] = 0;
}
return array;
}
private class DaliyTmp {
private int index;
private int val;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
}
}