682. Baseball Game

Leetcode link

解题思路

这题跟棒球没有半毛钱关系。。。。

本题给了我们一些字符串形式的数字,还有三个不同的运算符,自然而然的就能想到可以用栈这个数据结构先进先出的特性来处理

要注意的点在于变量的类型转换。

C++

class Solution {
 public:
  int calPoints(vector<string>& ops) {
    stack<int> stack;
    int res = 0;
    for (string ele : ops) {
      if (ele == "C") {
        stack.pop();
      } else if (ele == "D") {
        // 对字符串用乘法会自动转成数字
        stack.push(stack.top() * 2);
      } else if (ele == "+") {
        int value1 = stack.top();
        stack.pop();
        int value2 = stack.top();
        stack.push(value1);
        // 加法也是
        stack.push(value1 + value2);
      } else {
        // 需要显式转换为数字
        stack.push(stoi(ele));
      }
    }
    while (!stack.empty()) {
      res += stack.top();
      stack.pop();
    }
    return res;
  }
};

Javascript

/**
 * @param {string[]} ops
 * @return {number}
 */
var calPoints = function(ops) {
    let res = 0;
    let stack = [];
    for(let ele of ops) {
        switch (ele) {
            case "C":
                stack.pop();
                break;
            case "D":
                    // js 对数字形式的字符串用乘法会类型转换为数字
                stack.push(stack[stack.length-1] * 2);
                break;
            case "+":
                let value1 = stack[stack.length-1];
                let value2 = stack[stack.length-2];
                    // 必须显式类型转换,不然会字符串拼接
                stack.push(Number(value1) + Number(value2));
                break;
            default :
                    // 显式转换
                stack.push(Number(ele));
        }
    }
    for(let num of stack) {
        res+=num;
    }
    return res;
};

results matching ""

    No results matching ""