题目
给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。
表达式仅包含非负整数,+, - ,,/ 四种运算符和空格 。 整数除法仅保留整数部分。 * *
示例 1:
输入: “3+2X2”
输出: 7
import java.util.Stack;public class Code {public int calculate(String s) {Stack<Integer> data_stack = new Stack<>();Stack<Character> char_stack = new Stack<>();int length = s.length();int i = 0;while (i < length){char c = s.charAt(i);if (c == ' '){ //空格直接跳过i++;} else if (checkNumber(c)){ //如果是数字,处理如多个数字的情况 如333+1中的333int tmp = 0;while (i < length && checkNumber(s.charAt(i))){tmp = tmp * 10 + (s.charAt(i) - '0');i++;}data_stack.push(tmp);} else if (c == '('){ //左括号 直接入栈char_stack.push(c);i++;} else if (c == ')'){ //右括号 出栈计算 直到碰到'('为止while (!char_stack.isEmpty() && char_stack.peek() != '('){fetchAndCol(data_stack,char_stack);}char_stack.pop(); //弹出'('i++;} else {//如果字符栈为空 或者 运算字符 优先级 大于 栈顶字符,则运算字符直接入栈if (char_stack.isEmpty() || checkChar(c,char_stack.peek())){char_stack.push(c);} else {//优先级: 运算字符 <= 栈顶字符 ,则拿数字栈的前两个数字和栈顶字符栈计算,并把结果压入数字栈while (!char_stack.isEmpty() && !checkChar(c,char_stack.peek())){fetchAndCol(data_stack,char_stack);}char_stack.push(c); //最后再把字符入字符栈}i++;}}//如果字符栈不为空,则开始最后的计算,最后数字栈里只有一个最后计算的结果while (!char_stack.isEmpty()){fetchAndCol(data_stack,char_stack);}return data_stack.pop();}//计算数字栈和运算符栈public void fetchAndCol(Stack<Integer> data_stack,Stack<Character> char_stack){Integer pop1 = data_stack.pop();Integer pop2 = data_stack.pop();Character pop = char_stack.pop();Integer math = math(pop1, pop2, pop);data_stack.push(math);}public Integer math(Integer number1,Integer number2,char c){if (c == '+') return number1 + number2;if (c == '-') return number2 - number1;if (c == '*') return number1 * number2;if (c == '/') return number2 / number1;else return -1;}public boolean checkChar(char c,char top){if ((c == '*' || c == '/') && (top == '+' || top == '-')) return true;if (top == '(') return true; //栈顶运算符是'(' 也是返回trueelse return false;}//判断是否是数字public boolean checkNumber(char c){if (c >= '0' && c <= '9') return true;else return false;}
}