首页 > 代码库 > Leetcode 20. Valid Parentheses
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。