题解:模拟+栈(存放运算符)。
#include <cstdio>
#include <string>
#include <iostream>
#include <cstring>
#include <stack>
using namespace std;
const int N = 30;
int flag[N], now[N], value;
void init() {
value = 0;
memset(flag, 0, sizeof(flag));
for (int i = 1; i <= 26; i++)
now[i] = i;
}
int main() {
string str, str1;
stack<char> s;
while (getline(cin, str)) {
init();
int len = str.size();
str1 = "\0";
for (int i = 0; i < len; i++)
if (str[i] != ' ')
str1 += str[i];
len = str1.size();
for (int i = 0; i < len; i++) {
if (str1[i] >= 'a' && str1[i] <= 'z') {
int temp = str1[i] - 'a' + 1;
flag[temp] = 1;
if (s.empty())
value += now[temp];
else if (s.top() == '+') {
value += now[temp];
s.pop();
}
else if (s.top() == '-') {
value -= now[temp];
s.pop();
}
}
else if (i < len - 1 && ((str1[i] == '+' && str1[i + 1] != '+') || (str1[i] == '-' && str1[i + 1] != '-')))
s.push(str1[i]);
else if (i < len - 2 && (str1[i] == '+' && str1[i + 1] == '+' && str1[i + 2]== '+') || (str1[i] == '-' && str1[i + 1] == '-' && str1[i + 2]== '-'))
s.push(str1[i]);
else if (i < len - 1 && str1[i] == '+' && str1[i + 1] == '+') {
if (i > 0 && str1[i - 1] >= 'a' && str1[i - 1] <= 'z')
now[str1[i - 1] - 'a' + 1]++;
else if (i < len - 2 && str1[i + 2] >= 'a' && str1[i + 2] <= 'z')
now[str1[i + 2] - 'a' + 1]++;
i++;
}
else if (i < len - 1 && str1[i] == '-' && str1[i + 1] == '-') {
if (i > 0 && str1[i - 1] >= 'a' && str1[i - 1] <= 'z')
now[str1[i - 1] - 'a' + 1]--;
else if (i < len - 2 && str1[i + 2] >= 'a' && str1[i + 2] <= 'z')
now[str1[i + 2] - 'a' + 1]--;
i++;
}
}
printf("Expression: ");
cout << str << endl;
printf(" value = %d\n", value);
for (int i = 1; i < N; i++)
if (flag[i] == 1)
printf(" %c = %d\n", i + 'a' - 1, now[i]);
while (!s.empty())
s.pop();
}
return 0;
}