736.cc 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include <iostream>
  2. #include <map>
  3. #include <queue>
  4. #include <string>
  5. #include <vector>
  6. using std::deque;
  7. using std::map;
  8. using std::string;
  9. using std::vector;
  10. using std::cout; using std::endl;
  11. class Solution {
  12. public:
  13. int evaluate(string expression) {
  14. int pos = 0;
  15. return eval(expression, pos);
  16. }
  17. private:
  18. int eval(string exp, int& pos) {
  19. int val = 0;
  20. scopes.push_front(map<string, int>());
  21. if (exp[pos] == '(') pos++;
  22. string token = get_token(exp, pos);
  23. if (token == "add") {
  24. int val1 = eval(exp, ++pos);
  25. int val2 = eval(exp, ++pos);
  26. val = val1 + val2;
  27. } else if (token == "mult") {
  28. int val1 = eval(exp, ++pos);
  29. int val2 = eval(exp, ++pos);
  30. val = val1 * val2;
  31. } else if (token == "let") {
  32. vector<string> exps;
  33. while (pos < exp.size() && exp[pos] == ' ')
  34. exps.push_back(get_expression(exp, ++pos));
  35. int j = 0;
  36. for (int i = 0; i < exps.size() - 1; i += 2, j = 0) {
  37. string var = exps[i];
  38. int v = eval(exps[i + 1], j);
  39. scopes.front()[var] = v;
  40. }
  41. val = eval(exps.back(), j);
  42. } else if (isalpha(token[0])) {
  43. val = find_value(token);
  44. } else {
  45. val = atoi(token.c_str());
  46. }
  47. if (pos < exp.size() && exp[pos] == ')') pos++;
  48. scopes.pop_front();
  49. return val;
  50. }
  51. string get_token(string exp, int& pos) {
  52. int beg = pos;
  53. while (exp[pos] != ' ' && exp[pos] != ')') pos++;
  54. return exp.substr(beg, pos - beg);
  55. }
  56. string get_expression(string exp, int& pos) {
  57. int beg = pos, cnt = 0;
  58. while (pos < exp.size() && (cnt != 0 || (exp[pos] != ' ' && exp[pos] != ')'))) {
  59. char c = exp[pos++];
  60. if (c == '(') cnt++;
  61. if (c == ')') cnt--;
  62. }
  63. return exp.substr(beg, pos - beg);
  64. }
  65. int find_value(string token) {
  66. for (auto it = scopes.cbegin(); it != scopes.cend(); ++it)
  67. if (it->count(token))
  68. return it->at(token);
  69. return 0;
  70. }
  71. deque<map<string, int>> scopes;
  72. };
  73. // (add 1 (let x 2 x))
  74. int main() {
  75. Solution* sol = new Solution();
  76. cout << sol->evaluate("mult (add (add 1 3) 4) 5") << endl;
  77. cout << sol->evaluate("let x 3 y 9 x 1 x 4 (add x (let x 2 (add (add 1 x) 4)))") << endl;
  78. cout << sol->evaluate("(let x 1 y 2 x (add x y) (add x y))") << endl;
  79. return 0;
  80. }