百度笔试题,这是当时提交的代码,不过当中存在一个比较严重的问题,就是映射成字符的数目默认是有限的26,还好测试案例没有超过我预设的范围。
思路是转换为后缀表达式,然后求值。
#include<iostream>
#include <string>
#include <stack>
#include <map>
using namespace std;
#define LOCAL
map<char,int> myMap;
int calculate(string backStr){
stack<int> tmp;
for(int i=0;i<backStr.size();i++){
char c = backStr[i];
if(backStr[i]>='a'&&backStr[i]<='z'){
tmp.push(myMap[backStr[i]]);
}
else{
int right = tmp.top(); tmp.pop();
int left = tmp.top();tmp.pop();
int res =0;
switch(backStr[i]){
case '+' : res =left+right;break;
case '-' : res = left-right;break;
case '*' : res = left*right;break;
case '/' : res = left/right;break;
}
tmp.push(res);
}
}
return tmp.top();
}
// map char to int
string preSetting(string str){
myMap.clear();
int i=0;
char CurrentChar='a';
string newStr="";
while(i<str.size())
{
int num=0;
while(i<str.size()&& str[i]>='0'&&str[i]<='9'){
num=num*10+str[i]-'0';
i++;
}
newStr+=CurrentChar;
myMap.insert(make_pair<char,int>(CurrentChar,num));
while(i<str.size()&& (!(str[i]>='0'&&str[i]<='9'))){
newStr+=str[i];
++i;
}
CurrentChar++;
}
return newStr;
}
void analString(string str,string& backStr) {
backStr ="";
stack<char> mystack;
for (int i = 0; i < str.length(); i++) {
char c = str[i];
if (c == '+' || c == '-') {
if (mystack.empty()) {
mystack.push(c);
} else {
while (!mystack.empty() && (mystack.top()=='*' || mystack.top()=='/'|| mystack.top() == '+' || mystack.top() == '-')) {
//cout<<mystack.top();
backStr+=mystack.top();
mystack.pop();
}
mystack.push(c);
}
} else if (c == '*' || c == '/') {
if (mystack.empty() || mystack.top() == '+'|| mystack.top() == '-') {
mystack.push(c);
} else {
while (!mystack.empty() && (mystack.top() == '*' || mystack.top() == '/')) {
//cout<<mystack.top();
backStr+=mystack.top();
mystack.pop();
}
mystack.push(c);
}
}else {
backStr+=c;
//cout<<c;
}
}
if (!mystack.empty()) {
while (!mystack.empty()) {
//cout<<mystack.top();
backStr+=mystack.top();
mystack.pop();
}
}
}
int main(){
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif
string input;
while(cin>>input){
string backStr;
string newStr = preSetting(input);
analString(newStr,backStr);
//cout<<backStr;
cout<<calculate(backStr)<<endl;
}
#ifdef LOCAL
system("pause");
#endif
}