太菜了,写复杂了,先将表达式转换成逆波兰,再进行的运算 class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ int solve(string s) { // write code here stack stack1; stack q; vector str; string s1 = ""; for (int i = 0; i < s.size(); i++ ) { if (s[i] == '+' || s[i] == '-' || s[i] == '*' ) { if (s1.size() > 0) { str.push_back(s1); s1 = ""; } if (i == 0) { s1 +='-'; }else if (stack1.empty()){ // cout << s[i] << " "; stack1.push(s[i] ); }else if (s[i] < stack1.top()) { // cout << "121"; stack1.push(s[i]); }else if (s[i] > stack1.top()) { while (true) { char a = stack1.top(); if (a == '(')break; if (a > s[i])break; string ssss ; ssss+= a; str.push_back(ssss); stack1.pop(); if (stack1.size() == 0)break; } stack1.push(s[i]); }else if (s[i] == stack1.top()) { char a = stack1.top(); string ssss ; ssss+= a; str.push_back(ssss); stack1.pop(); stack1.push(s[i]); } }else if (s[i] == '(') { stack1.push('('); }else if (s[i] == ')') { str.push_back(s1); s1 = ""; while (true) { char a = stack1.top(); // cout << a << "=a"; if (a == '('){ stack1.pop(); break; } string ssss ; ssss+= a; str.push_back(ssss); stack1.pop(); if (stack1.size() == 0)break; } // stack1.pop(); }else { s1 += s[i]; } } str.push_back(s1); // cout << ssss; while (!stack1.empty()) { char a = stack1.top(); string ssss ; ssss+= a; str.push_back(ssss); stack1.pop(); } // str.push_back(ssss + ""); for (string ss : str) { cout << ss << ""; } cout << "\n"; int i = 0; for (string ss : str) { // cout << i++ << "\n"; if(ss != ""){ if (ss != "+" && ss != "-" && ss != "*") { q.push(atoi(ss.c_str())); // cout << atoi(ss.c_str()) << " " << ss << "\n"; } else{ if (ss == "+") { int a = q.top(); q.pop(); int b = q.top(); q.pop(); q.push(b + a); cout << q.top(); }else if (ss == "-") { int a = q.top(); q.pop(); int b = q.top(); q.pop(); q.push(b - a); cout << q.top() << " "; }else if (ss == "*") { int a = q.top(); q.pop(); int b = q.top(); q.pop(); q.push(b * a); cout << q.top(); } } } } return q.top(); return 0; } };