Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
Some examples:
“1 + 1” = 2
” 2-1 + 2 ” = 3
“(1+(4+5+2)-3)+(6+8)” = 23
题意:计算一个表达式的值,运算符只含有( ) + -
这道题的难易程度是medium,自己还是墨迹了2个小时
最开始的时候想的是找到一组括号,根据括号对数来确定一个括号域内的数,但是这样实现起来感觉有点麻烦,所以就网上搜索发现有后缀和中缀以及前缀这种算法。附上链接:[http://blog.csdn.net/antineutrino/article/details/6763722 ]
讲解的非常详细
根据讲解对算法进行实现如下:
int calculate(string s) {
stack<char> s1;//保存运算符
stack<string> s2;//保存数字,由于考虑到多位数所以用string
string temp;
string stemp;
for (int i = 0; i < s.length(); ++i)
{
if (s[i] ==' ')
{
continue;
}
if (s[i]>='0'&&s[i]<='9')
{
string temp1;
temp1 += s[i];
stemp += temp1;
continue;
}
if (stemp.length()>0)
{
s2.push(stemp);
stemp.clear();
}
if (s1.empty())
{
s1.push(s[i]);//遇到运算符就判断是否有数字
continue;
}
if (s[i]=='(')
{
s1.push(s[i]);
continue;
}
if (s[i]==')')
{
while (s1.top() != '(')
{
string temp1;
temp1 += s1.top();
s1.pop();
s2.push(temp1);
}
s1.pop();
continue;
}
if (eq(s[i]) && s1.top() == '(')
{
s1.push(s[i]);
continue;
}
if (eq(s[i])&&eq(s1.top()))
{
string temp1;
temp1 += s1.top();
s2.push(temp1);
s1.pop();
s1.push(s[i]);
continue;
}
}
if (stemp.length() > 0)//当最后一个是数字时
{
s2.push(stemp);
stemp.clear();
}
while (!s1.empty())//确保运算符全部被塞进s2
{
string temp1;
temp1 += s1.top();
s2.push(temp1);
s1.pop();
}
stack<string> st;
while (!s2.empty())
{
st.push(s2.top());//将stack里面的元素翻转
s2.pop();
}
int tot = 0;
while (!st.empty())
{
if (eq(st.top()))
{
int n1 = str_int(s2.top());
s2.pop();
int n2 = str_int(s2.top());
s2.pop();
int nt = 0;
if (st.top()=="+")
{
nt = n1 + n2;
}
else
{
nt = n2 - n1;
}
string snt = to_string(nt);
s2.push(snt);
st.pop();
}
else
{
s2.push(st.top());
st.pop();
}
}
int ret = 0;
ret = str_int(s2.top());//s2里面最终会有一个数字,这个数字就是最终的计算结果
return ret;
}
bool eq(char a)
{
if (a=='+'||a=='-')
{
return true;
}
return false;
}
bool eq(string a)//重载,判断string
{
if (a == "+" || a == "-")
{
return true;
}
return false;
}
int str_int(string s)//将string转化为int,注意计算的时候会有负数产生
{
int i = 0;
if (s[0]=='-')
{
i = 1;
}
int ret = 0;
for (; i < s.length();++i)
{
int temp = s[i] - '0';
ret = ret * 10 + temp;
}
if (s[0]=='-')
{
ret = 0 - ret;
}
return ret;
}
Happy Day~