> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/20.valid_parentheses.md).

# 20.Valid Parentheses

**20.Valid Parentheses**

难度:Easy

> 给定一个只包括 '('，')'，'{'，'}'，'\['，']' 的字符串，判断字符串是否有效。

有效字符串需满足： 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。

```
示例 1:

输入: "()"
输出: true
示例 2:

输入: "()[]{}"
输出: true
示例 3:

输入: "(]"
输出: false
示例 4:

输入: "([)]"
输出: false
示例 5:

输入: "{[]}"
输出: true 
```

方法：使用堆栈判断所有括号即可。代码如下：

```
class Solution {
public:
    bool isValid(string s) {
        stack<char> ss;
        for(int i=0;i<s.length();i++)
        {
            if(s[i] == '(' || s[i] == '{' || s[i]=='[')
                ss.push(s[i]);
            else if(ss.empty())
                return false;
            else if(s[i]==')')
            {
                if(ss.top()=='(')
                    ss.pop();
                else
                    return false;
            }
                  else if(s[i]==']')
            {
                if(ss.top()=='[')
                    ss.pop();
                else
                    return false;
            }
                  else if(s[i]=='}')
            {
                if(ss.top()=='{')
                    ss.pop();
                else
                    return false;
            }

        }
        if(ss.empty()) return true;
        return false;
    }
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/20.valid_parentheses.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
