LeetCode 20. Valid Parentheses


質問する


👉 20. Valid Parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

解答方法

  • "(,{,[)スタックに格納されます.
  • スタックが空の場合、falseが返されます.
    「」と入力した場合、カッコは完了しません.
  • ")、}、"」が表示されると、スタックの一番上の文字に比べてカッコが完了すると、スタックからポップアップされます.
  • コード#コード#

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> list;
            bool result = false;
            for (int i = 0; i < s.size(); i++) {
                char c = s[i];
                if (c == '(' || c == '{' || c == '[') {
                    list.push(c);
                }
                if (list.empty()) {
                    return false;
                }else if (c == ')' || c == '}' || c == ']') {
                    char peek = list.top();
                    cout << c <<", " << peek << endl;
                    if (c == ')' && peek == '(') {
                        list.pop();
                    } else if (c == '}' && peek == '{') {
                        list.pop();
                    } else if (c == ']' && peek == '[') {
                        list.pop();
                    } else {
                        return false;
                    }
                }
    
            }
            return list.empty();
        }
    };