题解 | #表达式求值#
表达式求值
http://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve (String s) { s = "(" + s + ")" ; return calKuoHao(s) ; } //计算括号里面表达式的值 int ss = 0 ; public int calKuoHao(String str) { if(ss >= str.length()) return 0 ; Stack<Integer> num = new Stack() ; Stack<Character> ops = new Stack<>() ; //处理 -23 +23这种情况 if(isJiaJian(str.charAt(ss))) { int i = ss + 1 ; while(isNum(str.charAt(i))) { i ++ ; } num.push(Integer.parseInt(str.substring(ss , i))) ; ss = i ; } // (-26*(3-4)*(2+3))*5 while(ss < str.length()) { char ch = str.charAt(ss) ; if(isJiaJian(ch) || isChen(ch)) { ops.push(ch) ; ss ++ ; } else if(isNum(ch)) { int i = ss + 1 ; while(i < str.length() && isNum(str.charAt(i))) { i ++ ; } int cur_num = Integer.parseInt(str.substring(ss , i)) ; //检查运算符 while(!ops.isEmpty() && isChen(ops.peek())) { int left = num.pop() ; int right = cur_num ; char op = ops.pop() ; cur_num = cal(left , op , right) ; } if(!ops.isEmpty() && ops.peek() == '-') { ops.pop() ; ops.push('+') ; num.push(0-cur_num) ; } else { num.push(cur_num) ; } ss = i ; } else if(ch == '(') {//是“(” ,递归 ss ++ ; int kuohao_val = calKuoHao(str) ; //检查运算符 while(!ops.isEmpty() && isChen(ops.peek())) { int left = num.pop() ; int right = kuohao_val ; char op = ops.pop() ; kuohao_val = cal(left , op , right) ; } num.push(kuohao_val) ; } else {//右括号 ) ss ++ ; break ; } } while(!ops.isEmpty()) { int right = num.pop() ; int left = num.pop() ; char op = ops.pop() ; int val = cal(left , op ,right) ; num.push(val) ; } return num.pop() ; } public boolean isNum(char ch) { return ch <= '9' && ch >= '0' ; } public boolean isJiaJian(char ch) { return ch == '+' || ch == '-' ; } public boolean isChen(char ch) { return ch == '*' ; } public int cal(int left , char op , int right) { switch(op) { case '+':return left + right ; case '-':return left - right ; case '*':return left * right ; } return 0 ; } }
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录