to do
完又有点强迫症了。。
30号准备考试吧先乖乖
1] Valid Parentheses
prettier
bool isValid(string s) {
stack<char> stk;
for (char& c:s) {
if (stk.empty() || c=='(' || c=='[' || c=='{') {
stk.push(c);
} else if ( ( c==')' && stk.top()!='(' )
|| ( c==']' && stk.top()!='[' )
|| ( c=='}' && stk.top()!='{' ) ) {
return false;
} else {
stk.pop();
}
}
return stk.empty();
}
4] Evaluate Reverse Polish Notation
string("blaj").find(char or str) return returns string::npos. on not found (cast to -1)
正常的写更快,可是看到lambda expression写法好鸡冻~~开启新世界
int evalRPN(vector<string>& tokens) {
unordered_map<string, function<int (int, int)>> opm = {
{"+", [](int a, int b) { return a+b; } },
{"-", [](int a, int b) { return a-b; } },
{"*", [](int a, int b) { return a*b; } },
{"/", [](int a, int b) { return a/b; } }
};
stack<int> stk;
for (auto s:tokens) {
if (string("+-*/").find(s)!=-1) {
int p2 = stk.top();
stk.pop();
int p1 = stk.top();
stk.pop();
stk.push( (opm[s])(p1, p2) );
} else {
stk.push(stoi(s));
}
}
return stk.top();
}
网友评论