您的位置:首页 > 其它

leetcode:Basic Calculator

2015-06-13 13:30 357 查看
写一个支持+-和()的运算表达式的求解,因为题目比较简单,直接穷举计算,没有使用到优先级判断了

import java.util.HashMap;
import java.util.Scanner;
import java.util.Stack;

public class Solution {

public int calculate(String s) {
Stack<Integer> nums = new Stack<Integer>();
Stack<Character> operation = new Stack<Character>();
int num = 0;
//s = "(0+" + s + ")";
s = "(" + s + ")";
char[] ch = s.toCharArray();
for(int i = 0 ; i < ch.length;++i){
char c = ch[i];
if(Character.isDigit(ch[i])){
do{
num = num * 10 + ch[i++] - '0';
}while(i < ch.length && Character.isDigit(ch[i]));
--i;
nums.push(num);
num = 0;
continue;
}
if(c == ')'){
char topOp = operation.pop();
if(topOp == '('){
continue;
}
int b = nums.pop();
int a = nums.pop();
nums.push(doOp(a, topOp, b));
operation.pop();
}else if(c == '('){
operation.push(c);
}else if(c == '+' || c == '-'){
char topOp = operation.peek();
if(topOp == '('){
operation.push(c);
continue;
}
int a = nums.pop();
int b = nums.pop();
nums.push(doOp(b, topOp, a));
operation.pop();
operation.push(c);
}
}
return nums.pop();
}

public int doOp(int a, char op, int b){
if(op == '-') b = -b;
return a + b;
}

public static void main(String[] args)throws Exception{
String s = "";
Scanner cin = new Scanner(System.in);
Solution solution = new Solution();
while(!s.equals("bye")){
s = cin.nextLine();
int ans = solution.calculate(s);
System.out.println(ans);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: