6.29-30 validParenthesis & reversePolish dpX2LATER!!

to do

6.29-30 validParenthesis & reversePolish dpX2LATER!!_第1张图片

完又有点强迫症了。。
30号准备考试吧先乖乖

1] Valid Parentheses

prettier

    bool isValid(string s) {
        stack 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& tokens) {
        unordered_map> 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 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();
    }  

你可能感兴趣的:(6.29-30 validParenthesis & reversePolish dpX2LATER!!)