day11 | 栈与队列part02

20. 有效的括号

其实一个只能删一个,不用写while

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char> umap;
        umap[')'] = '(';
        umap[']'] = '[';
        umap['}'] = '{';

        stack<char>sta;
        for (auto i : s)
        {
            if (umap.count(i))
            {
                if (sta.empty()) return false;
                if (sta.top() != umap[i])
                    return false;
                sta.pop();
            }    
            else 
            {
                sta.push(i);
            }
        }
        return sta.empty();
    }
};

1047. 删除字符串中的所有相邻重复项

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> sta;
        for (int i = 0; i < s.size(); i ++)
        {
            if (sta.empty()) sta.push(s[i]);
            else
            {
                if (s[i] == sta.top())
                {
                    sta.pop();
                }
                else
                    sta.push(s[i]);
            }
        }
        string res;
        while (sta.size())
        {
            res.push_back(sta.top());
            sta.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

150. 逆波兰表达式求值

class Solution {
public:
    // s1 [ch] s2
    int solve(string s1, string s2, string ch)
    {
        int num1 = atoi(s1.c_str());
        int num2 = atoi(s2.c_str());
        int res = 0;
        if (ch == "+") res = num1 + num2;
        else if (ch == "-") res = num1 - num2;
        else if (ch == "*") res = num1 * num2;
        else if (ch == "/") res = num1 / num2;
        return res;
    }

    int evalRPN(vector<string>& tokens) {
        unordered_set<string> uset = {"+", "-", "*", "/"};
        stack<string> sta;
        for (int i = 0; i < tokens.size(); i ++)
        {
            // 标点符号
            if (uset.count(tokens[i]))
            {
                string s2 = sta.top();
                sta.pop();
                string s1 = sta.top();
                sta.pop();

                int x = solve(s1, s2, tokens[i]);
                string s3 = to_string(x);
                sta.push(s3);
            }
            else
            {
                sta.push(tokens[i]);
            }
        }
        string res = sta.top();
        return atoi(res.c_str());
    }
};
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇