下面是原题:
表达式求值,一个字符串只由'+','-',和‘0’-‘9’组成,并且'+','-'只作为二元
运算符。
bool calculate(const char* exp, int &result);
运算符。
bool calculate(const char* exp, int &result);
想了想,这个用STL做很简单,因为只有+号和-号,没有其他符号,只要从左向右即可,不需要用栈。存操作数的用双端队列,存操作符的用普通队列先进先出即可。
下面是我的解决代码:
#include <iostream>
#include <string>
#include <deque>
#include <queue>
using namespace std;
bool calculate( const char* str, int &result )
{
string s(str);
deque<int> operands;
queue<char> ops;
/* parse the string
* put the operands into a deque
* put the ops into a queue
*/
unsigned int i = 0, j = 0;
for( ; j != s.length() ; ++j )
{
if( s[j] != '+' && s[j] != '-' )
continue;
else
{
operands.push_back( atoi( s.substr(i, j - i ).c_str() ) );
ops.push(s[j]);
i = j + 1;
}
}
operands.push_back( atoi( (s.substr(i, j - i)).c_str() ) ); //push the last operands
/* do the calculation
* fetch two operands and one ops once.
* then put the result back into the head of the deque
*/
while( !ops.empty() )
{
int left = operands.front();
operands.pop_front();
int right = operands.front();
operands.pop_front();
int re = 0;
char temp = ops.front();
ops.pop();
if( temp == '+' )
re = left + right;
else
re = left - right;
operands.push_front(re);
}
result = operands.front();
return true;
}
int main(void)
{
int result;
calculate( "56+24-2+100-40", result);
cout<<result<<endl;
return 0;
}
#include <string>
#include <deque>
#include <queue>
using namespace std;
bool calculate( const char* str, int &result )
{
string s(str);
deque<int> operands;
queue<char> ops;
/* parse the string
* put the operands into a deque
* put the ops into a queue
*/
unsigned int i = 0, j = 0;
for( ; j != s.length() ; ++j )
{
if( s[j] != '+' && s[j] != '-' )
continue;
else
{
operands.push_back( atoi( s.substr(i, j - i ).c_str() ) );
ops.push(s[j]);
i = j + 1;
}
}
operands.push_back( atoi( (s.substr(i, j - i)).c_str() ) ); //push the last operands
/* do the calculation
* fetch two operands and one ops once.
* then put the result back into the head of the deque
*/
while( !ops.empty() )
{
int left = operands.front();
operands.pop_front();
int right = operands.front();
operands.pop_front();
int re = 0;
char temp = ops.front();
ops.pop();
if( temp == '+' )
re = left + right;
else
re = left - right;
operands.push_front(re);
}
result = operands.front();
return true;
}
int main(void)
{
int result;
calculate( "56+24-2+100-40", result);
cout<<result<<endl;
return 0;
}
不过真不好意思,那个返回值我也没用,我没有做最后的检查(如果字符串最后一个是操作符怎么办)。主要是考了STL一些容器的操作吧。没什么算法的难度。
=======================================================
【Python实现】
其实这个问题在脚本语言中很好解决,用一条语句就可以搞定了。。。