class Solution {
public:
int evalRPN(vector<string>& tokens) {
int m = tokens.size();
int i = 0;
int a = 0, b = 0;//分别表示符号两边的两个操作数
stack<int> st1;//存放数值的堆栈
while (i < m) {
if (!token(tokens[i]))
st1.push(stoi(tokens[i]));
else {//如果是符号
b = st1.top();
st1.pop();
a = st1.top();
st1.pop();
st1.push(count(a,b,tokens[i]));//将使用a和b以及符号计算所得的结果传入函数进行计算
}
i++;
}
return st1.top();
}
bool token(string s) {//描述是不是加减乘除等符号
if (s == "+" || s == "-" || s == "*" || s == "/")
return true;
else return false;//否则就表示是数字
}
int count(int a, int b, string s) {
if (s == "+")
return a + b;
if (s == "-")
return a - b;
if (s == "*")
return a * b;
if (s == "/")
return a / b;
}
};
int main() {
int n;
cin >> n;
vector<string> tokens(n);
for (int i = 0; i < n; i++) {
cin >> tokens[i];
}
Solution bb;
cout << bb.evalRPN(tokens);
return 0;
}
20. 有效的括号(通过)
思路:堆栈
效率:21.53%
程序代码:
class Solution {
public:
bool isValid(string s) {
int m = s.size();
int i = 0;
stack<char> st1;//建立堆栈
while (i < m) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
st1.push(s[i]);//将字符放进堆栈中
else if (st1.empty() || !com(st1.top(),s[i]))//如果一样就进行抛出
return false;
else
st1.pop();
i++;
}
return st1.empty();
}
bool com(char a, char b) {//检查两个字符是不是一对
if (a == '('&&b==')'|| a == '['&&b == ']' || a == '{'&&b == '}')
return true;
else
return false;
}
};
效率有点低,以下是优秀代码展示:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (int i = 0; i < s.length(); i++) {
char tem = s[i];
if (tem == '(') {
st.push(')');
} else if (tem == '{') {
st.push('}');
} else if (tem == '[') {
st.push(']');
} else {
if (st.empty() || tem != st.top()) {
return false;
} else {
st.pop();
}
}
}
if (st.empty()) {
return true;
} else {
return false;
}
}
};