标签:简洁 new 说明 style first ++ color 表达 blog
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 (
,右括号 )
,加号 +
,减号 -
,非负整数和空格
。
示例 1:
输入: "1 + 1" 输出: 2
示例 2:
输入: " 2-1 + 2 " 输出: 3
示例 3:
输入: "(1+(4+5+2)-3)+(6+8)" 输出: 23
说明:
eval
。一开始写的代码如下,太冗余了:
class Solution { public: int calculate(string s) { stack<int> s1; stack<char> s2; int curRes = 0; for (int i = 0; i < s.size(); ) { if (s[i] == ‘ ‘) { i++; } else if (s[i] == ‘+‘ || s[i] == ‘-‘ || s[i] == ‘(‘) { s2.push(s[i++]); } else if (isdigit(s[i])) { int tmp = 0, j = i; while (j < s.size() && isdigit(s[j])) { tmp = 10 * tmp + s[j++] - ‘0‘; } s1.push(tmp); i = j; if (!s2.empty() && s2.top() != ‘(‘) { char ctmp = s2.top(); s2.pop(); int second, first; second = s1.top(); s1.pop(); first = s1.top(); s1.pop(); curRes = ctmp == ‘+‘ ? first + second : first - second; s1.push(curRes); } } else { s2.pop();//( char op = ‘?‘; int first = 0, second; if (!s2.empty()) { op = s2.top(); s2.pop(); second = s1.top(); s1.pop(); if (!s1.empty()) { first = s1.top(); s1.pop(); } if (op == ‘+‘) { s1.push(first + second); } else if (op == ‘-‘) { s1.push(first - second); } else { s1.push(second); } } i++; } } return s1.empty()? 0: s1.top(); } };
后来在网上发现了更简洁的写法,参考https://www.cnblogs.com/newnoobbird/p/9627182.html。非常简洁,之利用了
class Solution { public: int calculate(string s) { int res=0,sign=1,n=s.size(); stack<int> st; for(int i=0;i<n;i++){ if(s[i]>=‘0‘){ int num=0; while(i<n&&s[i]>=‘0‘){ num=num*10+s[i++]-‘0‘; } res+=sign*num; i--; }else if(s[i]==‘+‘){ sign=1; }else if(s[i]==‘-‘){ sign=-1; }else if(s[i]==‘(‘){ st.push(res); st.push(sign); res=0; sign=1; }else if(s[i]==‘)‘){ res*=st.top(); st.pop(); res+=st.top(); st.pop(); } } return res; } };
标签:简洁 new 说明 style first ++ color 表达 blog
原文地址:https://www.cnblogs.com/hlk09/p/9736889.html