双栈一个用来放数字,一个用来放符号。其余看注释,90m,有点多,判断数字还可以优化下
public class Solution {
public int calculate(String s) {
Stack<Integer> number = new Stack<>();
Stack<Character> symbols = new Stack<>();
StringBuilder str = new StringBuilder();
int one = 0;
int two = 0;
s.replaceAll(" ","");//用来去除空格
char[] st = s.toCharArray();
for(int i=0;i<st.length;i++){
//用来把多位数字放到栈中
if(Character.isDigit(st[i])){
if(i<st.length-1){
//当不是最后一位数字时就可以比较后一位是不是数字,
//如果后一位是数字(说明是多位数字)
//就直接放入str中连起来
if(Character.isDigit(st[i+1])){
str.append(st[i]);
continue;
}
if(!Character.isDigit(st[i+1])){
str.append(st[i]);
number.push(Integer.parseInt(str.toString()));
str = new StringBuilder();
}
}
//到了最后一位(前提是数字,在条件中),
//不用管直接就放入str
if(i==st.length-1){
str.append(st[i]);
number.push(Integer.parseInt(str.toString()));
}
if(number.size()>1){
//普通的加减
if(symbols.peek()=='+'){
symbols.pop();
one = number.pop();
two = number.pop();
number.push(one+two);
}
else if(symbols.peek()=='-'){
symbols.pop();
one = number.pop();
two = number.pop();
number.push(two-one);
}
}
}
else if(st[i]=='('){
symbols.push('(');
}
else if(st[i]==')'){
//当是‘)’时肯定下一个会是'('所以直接删,然后看下一个
//符号是什么如果是+就+。。。如果是-就-
symbols.pop();
if(!symbols.isEmpty()){
if(symbols.peek()=='+'){
symbols.pop();
one = number.pop();
two = number.pop();
number.push(one+two);
}
else if(symbols.peek()=='-'){
symbols.pop();
one = number.pop();
two = number.pop();
number.push(two-one);
}
}
}
else if(st[i]=='+'){
symbols.push(st[i]);
}
else if(st[i]=='-'){
symbols.push(st[i]);
}
}
return number.peek();
}
}