calculator会想到stack,不同题目的处理方式不一样
227 Basic Calculator II
class Solution {
public:
int calculate(string s) {
if(s.empty()) return 0;
stack<int> st;
char sign = '+';
int cur = 0;
for(int i=0; i<s.length(); i++){
if(isdigit(s[i])){
cur = cur*10 + s[i]-'0';
}
if(s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/' || i == s.length()-1){
if(sign == '+') st.push(cur);
if(sign == '-') st.push((-1)*cur);
if(sign == '*'){
int a1 = st.top(); st.pop();
st.push(a1 * cur);
}
if(sign == '/'){
int a1 = st.top(); st.pop();
st.push(a1 / cur);
}
cur = 0;
if(i != s.length()-1) sign = s[i];
}
}
int ret = 0;
while(!st.empty()){
ret += st.top(); st.pop();
}
return ret;
}
};
Leetcode 150 Evaluate Reverse Polish Notation:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
if(tokens.empty()) return 0;
stack<int> st;
for(int i=0; i<tokens.size(); i++){
if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/"){
if(st.empty()) return 0;
int num1 = st.top(); st.pop();
if(st.empty()) return 0;
int num2 = st.top(); st.pop();
st.push(eval(num1, num2, tokens[i]));
}else{
st.push(stoi(tokens[i]));
}
}
return st.top();
}
int eval(int num1, int num2, string sign){
if(sign == "+") return num2 + num1;
else if(sign == "-") return num2 - num1;
else if(sign == "*") return num2 * num1;
else return num2 / num1;
}
};
网友评论