classSolution { private: stack<char> cs; public: boolisPair(char a, char b){ // 判断a是否为b的对应左侧符号 if (a == '(' && b == ')') returntrue; if (a == '[' && b == ']') returntrue; if (a == '{' && b == '}') returntrue; returnfalse; }
boolisValid(string s){ for (char c : s) { // 遍历字符串中的字符 if (c == '(' || c == '{' || c == '[') cs.push(c); // 若为左侧字符,则入栈 else { // 若为右侧字符 if (cs.empty()) returnfalse; // 栈中没有内容,不匹配 char topChar = cs.top(); // 判断栈顶符号是否和当前的右侧符号匹配 if (isPair(topChar, c)) cs.pop(); elsereturnfalse; } } if (!cs.empty()) returnfalse; // 遍历完成后,栈若不为空,则仍不满足条件 returntrue; } };
classSolution { public: boolhasPriority(char a, char b){ // 对比运算符优先级 if ((a == '*' || a == '/') && (b == '+' || b == '-')) returntrue; returnfalse; }
intevalRPN(vector<string>& tokens){ stack<int> nums; stack<char> ops; for (string s : tokens) { if (s != "+" && s != "-" && s != "*" && s != "/") nums.push(stoi(s)); // 将遇到的每个运算数入栈 else { char c = s[0]; if (ops.empty() || !hasPriority(s[0], ops.top())) { // 满足进行运算的条件 int a = nums.top(); nums.pop(); int b = nums.top(); nums.pop(); int num = 0; if (c == '+') num = a + b; elseif (c == '-') num = b - a; elseif (c == '*') num = a * b; elseif (c == '/') num = b / a; nums.push(num); } else { ops.push(c); } } } return nums.top(); } };