题目链接:https://leetcode.com/problems/basic-calculator/#/description
题意:计算一个只含有括号、加减、非负数的表达式。
用一个栈记数,一个栈记符号。
1 class Solution { 2 public: 3 int calculate(string s) { 4 int n = s.length(); 5 stack<int> st; 6 stack<char> op; 7 int ret = 0; 8 op.push(‘+‘); 9 for(int i = 0; i < n; i++) { 10 if(isdigit(s[i])) { 11 int x = 0; 12 while(isdigit(s[i])) x = x * 10 + s[i++] - ‘0‘; 13 i--; 14 char o = op.top(); op.pop(); 15 if(o == ‘+‘) ret += x; 16 else ret -= x; 17 } 18 else if(s[i] == ‘+‘ || s[i] == ‘-‘) op.push(s[i]); 19 else if(s[i] == ‘(‘) { 20 st.push(ret); 21 op.push(‘+‘); 22 ret = 0; 23 } 24 else if(s[i] == ‘)‘) { 25 char o = op.top(); op.pop(); 26 if(o == ‘+‘) ret += st.top(); 27 else ret = st.top() - ret; 28 st.pop(); 29 } 30 } 31 return ret; 32 } 33 };
时间: 2024-10-23 06:29:12