# 20. Valid Parentheses

## 題目原文

Given a string 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.

Note that an empty string is also considered valid.

#### Example 1:

```
Input: "()"
Output: true
```

#### Example 2:

```
Input: "()[]{}"
Output: true
```

#### Example 3:

```
Input: "(]"
Output: false
```

#### Example 4:

```
Input: "([)]"
Output: false
```

#### Example 5:

```
Input: "{[]}"
Output: true
```

## **解題思路**

{% hint style="info" %}

1. 善用[stack](http://www.cplusplus.com/reference/stack/stack/)。
2. 遇到左括弧先push到Stack裡，遇到右括弧再從Stack pop出左括弧。
3. pop出來的左括弧是否對應相對的右括弧。
4. 最後，判斷Stack是否為空。
   {% endhint %}

## 程式解答

```cpp
class Solution 
{
public:
    bool isValid(string s) 
    {
        std::stack<char> p;
        char temp;
        
        if (s.length() % 2 != 0)
            return false;
        
        for (int i = 0; i < s.length(); i++)
        {
            switch (s[i])
            {
                case '(':
                case '[':
                case '{':
                    p.push(s[i]);
                    break;
                case ')':
                    if (!p.size())
                        return false;
                    temp = p.top();
                    p.pop();
                    if (temp != '(')
                        return false;
                    break;
                case ']':
                    if (!p.size())
                        return false;
                    temp = p.top();
                    p.pop();
                    if (temp != '[')
                        return false;
                    break;
                case '}':
                    if (!p.size())
                        return false;
                    temp = p.top();
                    p.pop();
                    if (temp != '{')
                        return false;
                    break;
            }
        }
        if (!p.size())
            return true;
        return false;
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://stanley7342.gitbook.io/programming/leetcode/20.-valid-parentheses.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
