import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve (String s) { // write code here int ret = 0; int[] num = new int[s.length()]; int nu = 0; char[] symbol = new char[s.length()]; int sy = 0; for (int i = 0; i < s.length(); i++){ if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' || s.charAt(i) == '(' || s.charAt(i) == ')'){ if (sy == 0){ symbol[sy++] = s.charAt(i); }else{ switch(s.charAt(i)){ case '+': case '-': if (symbol[sy-1] == s.charAt(i) || symbol[sy-1] == '*'){ //出栈 switch(symbol[sy-1]){ case '+': num[nu-2] = num[nu-2] + num[nu-1]; nu--; sy--; break; case '-': num[nu-2] = num[nu-2] - num[nu-1]; nu--; sy--; break; case '*': num[nu-2] = num[nu-2] * num[nu-1]; nu--; sy--; break; } //入栈 symbol[sy++] = s.charAt(i); }else{ //入栈 symbol[sy++] = s.charAt(i); } break; case '*': if (symbol[sy-1] == s.charAt(i)){ //出栈 num[nu-2] = num[nu-2] * num[nu-1]; nu--; sy--; //入栈 symbol[sy++] = s.charAt(i); }else{ symbol[sy++] = s.charAt(i); } break; case '(': symbol[sy++] = s.charAt(i); break; case ')': //出栈 while(symbol[sy-1] != '('){ switch(symbol[sy-1]){ case '+': num[nu-2] = num[nu-2] + num[nu-1]; nu--; sy--; break; case '-': num[nu-2] = num[nu-2] - num[nu-1]; nu--; sy--; break; case '*': num[nu-2] = num[nu-2] * num[nu-1]; nu--; sy--; break; } } sy--; break; } } }else{ int tmp = s.charAt(i) - '0'; while((i+1) < s.length() && s.charAt(i + 1) <= '9' && s.charAt(i + 1) >= '0'){ tmp *= 10; tmp += s.charAt(++i) - '0'; } num[nu++] = tmp; } } while(sy != 0){ switch(symbol[sy-1]){ case '+': num[nu-2] = num[nu-2] + num[nu-1]; nu--; sy--; break; case '-': num[nu-2] = num[nu-2] - num[nu-1]; nu--; sy--; break; case '*': num[nu-2] = num[nu-2] * num[nu-1]; nu--; sy--; break; } } ret = num[0]; return ret; } }