Leetcode 20. Valid Parentheses
Posted Deribs4
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 20. Valid Parentheses相关的知识,希望对你有一定的参考价值。
20. Valid Parentheses
- Total Accepted: 128586
- Total Submissions: 418560
- Difficulty: Easy
Given a string containing just the characters ‘(‘
, ‘)‘
, ‘{‘
, ‘}‘
, ‘[‘
and ‘]‘
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
思路:利用栈来判断配对的括号,如果都可以配对成功,最后栈的元素数量应该为0。题目给定的字符串只包含括号,所以每次遇到是(‘,
‘{‘或者
‘[‘,直接入栈;遇到
‘]‘,
‘)‘
或者
‘]‘,只有当栈不为空&&栈顶元素与之配对时,才弹出栈,否则直接返回false。
代码:
1 class Solution { 2 public: 3 bool isValid(string s) { 4 stack<char> cs; 5 unordered_map<char, char> um; 6 um[‘(‘] = ‘)‘; 7 um[‘{‘] = ‘}‘; 8 um[‘[‘] = ‘]‘; 9 for (int i = 0; i < s.size(); i++) { 10 if (s[i] == ‘(‘ || s[i] == ‘{‘ || s[i] == ‘[‘) { 11 cs.push(s[i]); 12 continue; 13 } 14 if (!cs.empty() && um[cs.top()] == s[i]){ 15 cs.pop(); 16 continue; 17 } 18 return false; 19 } 20 return cs.empty(); 21 } 22 };
以上是关于Leetcode 20. Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode - 20. Valid Parentheses
[LeetCode]20. Valid Parentheses
[LeetCode]20 Valid Parentheses 有效的括号