C++实现LeetCode(20.验证括号)
[LeetCode] 20. Valid Parentheses 验证括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example 1:
Input: "()"Example 2:
Output: true
Input: "()[]{}"Example 3:
Output: true
Input: "(]"【C++实现LeetCode(20.验证括号)】Example 4:
Output: false
Input: "([)]"Example 5:
Output: false
Input: "{[]}"这道题让我们验证输入的字符串是否为括号字符串,包括大括号,中括号和小括号。这里需要用一个栈,开始遍历输入字符串,如果当前字符为左半边括号时,则将其压入栈中,如果遇到右半边括号时,若此时栈为空,则直接返回 false,如不为空,则取出栈顶元素,若为对应的左半边括号,则继续循环,反之返回 false,代码如下:
Output: true
方法一:
class Solution {public:bool isValid(string s) {stackparentheses; for (int i = 0; i < s.size(); ++i) {if (s[i] == '(' || s[i] == '[' || s[i] == '{') parentheses.push(s[i]); else {if (parentheses.empty()) return false; if (s[i] == ')' && parentheses.top() != '(') return false; if (s[i] == ']' && parentheses.top() != '[') return false; if (s[i] == '}' && parentheses.top() != '{') return false; parentheses.pop(); }}return parentheses.empty(); }};
方法二:
class Solution {public:bool isValid(string s) {int n = s.size(); if (n % 2 == 1) {return false; }unordered_mappairs = {{')', '('},{']', '['},{'}', '{'}}; stack stk; for (char ch: s) {if (pairs.count(ch)) {if (stk.empty() || stk.top() != pairs[ch]) {return false; }stk.pop(); }else {stk.push(ch); }}return stk.empty(); }};
到此这篇关于C++实现LeetCode(20.验证括号)的文章就介绍到这了,更多相关C++实现验证括号内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- java中如何实现重建二叉树
- leetcode|leetcode 92. 反转链表 II
- 人脸识别|【人脸识别系列】| 实现自动化妆