栈的一个经典应用例题就是《基本计算器》,这个算法手写过程我很熟悉,但是代码实现不是很熟手,因此复习阶段有必要把这个算法总结一下。
题目描述,输入一个字符串,包含 数字0-9,(,),+,-,*,/ 以及一些空格,保证输入的数据是合理的,不会出现语义错误,不会出现0作为除数,没有处理开头符号和左括号紧跟负号。
算法实现
#include <iostream>
#include <map>
#include <vector>
#include <stack>
using namespace std;
int cal(vector<string> words, map<char, int> m){
stack<int> nums;
stack<char> op;
for(int i=0;i<words.size();i++){
char c = words[i][0];
if(c>='0'&&c<='9'){
nums.push(stoi(words[i]));
}
else if(op.empty()||op.top()=='(')
op.push(c);
else{
while(!op.empty() && m[words[i][0]]<=m[op.top()]){
// 当前运算符的优先级小于等于符号栈顶运算符的优先级
if(op.top()=='('&&words[i][0]==')'){ // 碰到了左括号
op.pop(); //左括号出栈
break;
}
int b = nums.top();
nums.pop();
int a = nums.top();
nums.pop();
switch(op.top()){
case '+': a = a+b; break;
case '-': a = a-b; break;
case '*': a = a*b; break;
case '/': a = a/b; break;
default:
break;
}
nums.push(a); //计算之后再入栈
op.pop(); // 符号出栈
}
if(c!=')') // 如果当前符号是右括号不必入符号栈
op.push(c); //当前符号入栈
}
}
return nums.top();
}
int main() {
string input;
getline(cin, input);
map<char, int> m; //优先级定义
m['#'] = 0;
m['+'] = 1;
m['-'] = 1;
m['*'] = 2;
m['/'] = 2;
m['('] = 3;
m[')'] = 0;
input += '#';
// 1、词法分析,先把必要的单词分隔开来
vector<string> words;
string num;
for(int i=0;i<input.length();i++){
num = "";
while(i<input.length() && input[i]>='0'&&input[i]<='9'){
num += input[i++];
}
if(!num.empty()){
words.push_back(num);
i--;
continue;
}
char c = input[i];
if(c==' ') //空格直接跳过
continue;
else{
string s = "";
s += c;
words.push_back(s);
}
}
int ans = cal(words, m);
cout<<ans<<endl;
return 0;
}
CCF-CSP题目相关
二十四点
#include <iostream>
#include <stack>
#include <map>
using namespace std;
int main() {
int n;
cin>>n;
stack<int> nums;
stack<char> op;
map<char, int> m;
m['#'] = 0; //结束符
m['+'] = 1;
m['-'] = 1;
m['x'] = 2;
m['/'] = 2;
while(n--){
string str;
cin>>str;
str += '#';
for(auto c: str){
if(c>='0'&&c<='9')
nums.push(c-'0');
else if(op.empty()) //符号栈为空
op.push(c); //符号入栈
else{ //符号栈不空,则判断当前符号的优先级和栈顶符号的优先级
while(!op.empty()&&m[op.top()] >= m[c]){
//符号栈不为空,且符号栈顶的运算符优先级大于等于当前符号优先级
char token = op.top();
int b=nums.top();
nums.pop();
int a=nums.top();
nums.pop();
switch (token){
case '+':
a = a+b; break;
case '-':
a = a-b; break;
case 'x':
a = a*b; break;
case '/':
a = a/b; break;
default:
break;
}
nums.push(a); //计算后的数再压入栈
op.pop();
}
op.push(c); //当前符号入栈
}
}
if(nums.top()==24)
printf("Yes\n");
else
printf("No\n");
nums.pop(); //清空栈
op.pop();
}
return 0;
}