描述
请写一个整数计算器,支持加减乘三种运算和括号。
数据范围:0≤∣�∣≤1000≤∣s∣≤100,保证计算结果始终在整型范围内
要求:空间复杂度: �(�)O(n),时间复杂度 �(�)O(n)
示例1
输入:
"1+2"
复制返回值:
3
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
HashMap<Character, Integer> map=new HashMap<Character,Integer>(){{
put('-',1);
put('+',1);
put('*',2);
}};
public int solve (String s) {
// write code here
s=s.replaceAll(" ","");
char[] cs=s.toCharArray();
int n=s.length();
Deque<Integer> nums=new ArrayDeque<>();
nums.addLast(0);
Deque<Character> ops=new ArrayDeque<>();
for(int i=0;i<n;i++){
char c=cs[i];
if(c=='(') ops.addLast(c);
else if(c==')'){
while(!ops.isEmpty()){
if(ops.peekLast()!='(')
calc(nums,ops);
else {
ops.pollLast();
break;
}}
}else {
if(isNumber(c)){
int u=0;
int j=i;
while(j<n&&isNumber(cs[j])) u=u*10+(cs[j++]-'0');
nums.addLast(u);
i=j-1;
}else {
if(i>0&&(cs[i-1]=='('||cs[i-1]=='+'||cs[i-1]=='-')) {
nums.addLast(0);
}
while(!ops.isEmpty()&&ops.peekLast()!='('){
char prev=ops.peekLast();
if(map.get(prev)>=map.get(c)){
calc(nums,ops);
}else break;
}
ops.addLast(c);
}
}
}
while(!ops.isEmpty()&&ops.peekLast()!='(') calc(nums,ops);
return nums.peekLast();
}
void calc(Deque<Integer> nums,Deque<Character> ops){
if(nums.isEmpty()||nums.size()<2) return ;
if(ops.isEmpty()) return ;
int b=nums.pollLast() , a=nums.pollLast();
char op=ops.pollLast();
int ans=0;
if(op=='+') ans=a+b;
else if(op=='-') ans=a-b;
else if(op=='*') ans=a*b;
nums.addLast(ans);
}
boolean isNumber(char c){
return Character.isDigit(c);
}
}