Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 20. Valid Parentheses

Rain Hu

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:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Stack

unordered_map<char,char> map = {{'[',']'}, {'(',')'}, {'{','}'}};
bool isValid(string s) {
    stack<char> st;
    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '[' || s[i] == '(' || s[i] == '{') {    // 左括號推到 stack 上
            st.push(s[i]);
        } else {
            if (st.empty() || s[i] != map[st.top()]) return false;  // 右括號檢查 stack 是否有配對到
            st.pop();
        }
    }
    return st.empty();  // 檢查 stack 是否為空
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2024. Maximize the Confusion of an Exam
Next
[LeetCode] 2779. Maximum Beauty of an Array After Applying Operation