227. 基本计算器 II
1.在字符串中提取整数方法
2.加减乘除的判断(无括号)
3.单栈
class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
char sign = '+';
for(int i=0;i<s.length();++i){
if (s.charAt(i) == ' ') continue;
if(s.charAt(i)>='0'&&s.charAt(i)<='9'){
int num = 0;
while(i<s.length()&&s.charAt(i)>='0'&&s.charAt(i)<='9'){
num = num*10 + s.charAt(i)-'0';
++i;
}
--i;
if(sign == '*') stack.push(stack.pop()*num);
else if(sign == '/') stack.push(stack.pop()/num);
else if(sign == '+') stack.push(num);
else if(sign == '-') stack.push(-num);
}else{
sign = s.charAt(i);
}
}
int res = 0;
while(!stack.isEmpty()){
res +=stack.pop();
}
return res;
}
}
224. 基本计算器
1.双栈处理,一个栈存临时计算结果,一个栈存符号
2.遇到‘(’ 入栈,数字和数字后边的符号 同时入相应的栈;
3.遇到‘)’出栈,符号栈顶元素 乘以 临时计算结果 加 数字栈
4.否则就一直计算临时计算结果
5.关键在于 if else 一定要按逻辑出现。注意多个if与 if…else if …else 的区别
class Solution {
public int calculate(String s) {
Stack<Integer> numstack = new Stack<>();
Stack<Integer> signstack = new Stack<>();
int ans = 0;
int sign = 1;
char[] chars = s.toCharArray();
int length = chars.length;
for(int i=0;i<length;++i){
if(chars[i] == ' ') continue;
if(chars[i] == '+'||chars[i] == '-') sign = chars[i] == '+'?1:-1;
else if(chars[i]>='0'&&chars[i]<='9'){
int n = 0;
while(i<length&&chars[i]>='0'&&chars[i]<='9'){
n = n*10+chars[i]-'0';
++i;
}
--i;
ans+=sign*n;
}else if(chars[i] == '('){
numstack.push(ans);
signstack.push(sign);
ans = 0;
sign = 1;
}else ans = numstack.pop()+ans*signstack.pop();
}
return ans;
}
}
两个栈实现队列
1.插入无所谓
2.取出时需要判断第二个栈是否为空,如果为空,需要将第一个栈的数弄到第二个栈中
3.第一个栈往第二个栈倒数据时,要保证第二个栈为空才能保证队列顺序正确
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.add(node);
}
public int pop() {
if(stack2.isEmpty())
while(!stack1.isEmpty()){
stack2.add(stack1.pop());
}
return stack2.pop();
}
}