# 有效的括号

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

 

示例 1:

输入:s = "()"
输出:
true

示例 2:

输入:s = "()[]{}"
输出:
true

示例 3:

输入:s = "(]"
输出:
false

示例 4:

输入:s = "([)]"
输出:
false

示例 5:

输入:s = "{[]}"
输出:
true

 

提示:

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

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

 

示例 1:

输入:s = "()"
输出:
true

示例 2:

输入:s = "()[]{}"
输出:
true

示例 3:

输入:s = "(]"
输出:
false

示例 4:

输入:s = "([)]"
输出:
false

示例 5:

输入:s = "{[]}"
输出:
true

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; string s = "([)]"; bool res; res = sol.isValid(s); cout << res; return 0; } ``` ## 答案 ```cpp class Solution { public: bool isValid(string s) { stack symbols; for (int i = 0; i < s.size(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') symbols.push(s[i + 1]); else { if (symbols.size() == 0) return false; char match; if (s[i] == ')') match = '('; else if (s[i] == ']') match = '['; else if (s[i] == '}') match = '{'; char c = symbols.top(); symbols.pop(); if (c != match) return false; } } if (symbols.size() != 0) return false; return true; } }; ``` ## 选项 ### A ```cpp class Solution { public: bool isValid(string s) { if (s.size() % 2 != 0) return false; if (s.size() == 0) return true; string temp; temp.push_back(s[0]); for (int i = 1; i < s.size(); ++i) { int k = temp.size() - 1; if (temp[k] == '(' && s[i] == ')') temp.pop_back(); else if (temp[k] == '[' && s[i] == ']') temp.pop_back(); else if (temp[k] == '{' && s[i] == '}') temp.pop_back(); else temp.push_back(s[i]); } return temp.size() == 0; } }; ``` ### B ```cpp class Solution { public: bool isValid(string s) { if (s.length() == 0) { return true; } if (s.length() % 2 != 0) { return false; } stack st; for (auto item : s) { if (item == '(' || item == '[' || item == '{') st.push(item); if (st.empty()) return false; if (item == ')') { if (st.top() == '(') { st.pop(); } else return false; } else if (item == ']') { if (st.top() == '[') { st.pop(); } else return false; } else if (item == '}') { if (st.top() == '{') { st.pop(); } else return false; } } return st.empty(); } }; ``` ### C ```cpp class Solution { public: bool isValid(string s) { stack data; map match = {{'{', '}'}, {'[', ']'}, {'(', ')'}}; for (auto &i : s) { if (i == '(' || i == '[' || i == '{') { /* code */ data.push(i); } else { if (data.empty()) return false; char top = data.top(); data.pop(); if (match[top] != i) return false; } } return data.size() == 0; } }; ```