[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.
Note that an empty string is also considered valid.
Example 1:
- Input: "()"
- Output: true
Example 2:
- Input: "()[]{}"
- Output: true
Example 3:
- Input: "(]"
- Output: false
Example 4:
- Input: "([)]"
- Output: false
Example 5:
- Input: "{[]}"
- Output: true
输入的字符串只含有'('
, ')'
, '{'
, '}'
, '['
, ']',验证字符串
是否配对合理。
解法:栈Stack,经典的使用栈的题目。遍历字符串,如果为左括号,将其压入栈中,如果遇到为右括号,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左括号,是合法的继续循环,否则返回false。
Java: Time: O(n), Space: O(n)
- public static boolean isValid(String s) {
- HashMap<Character, Character> map = new HashMap<Character, Character>();
- map.put('(', ')');
- map.put('[', ']');
- map.put('{', '}');
- Stack<Character> stack = new Stack<Character>();
- for (int i = 0; i < s.length(); i++) {
- char curr = s.charAt(i);
- if (map.keySet().contains(curr)) {
- stack.push(curr);
- } else if (map.values().contains(curr)) {
- if (!stack.empty() && map.get(stack.peek()) == curr) {
- stack.pop();
- } else {
- return false;
- }
- }
- }
- return stack.empty();
- }
Java:
- public boolean isValid(String s) {
- Stack<Character> stack = new Stack<Character>();
- for (char c : s.toCharArray()) {
- if (c == '(')
- stack.push(')');
- else if (c == '{')
- stack.push('}');
- else if (c == '[')
- stack.push(']');
- else if (stack.isEmpty() || stack.pop() != c)
- return false;
- }
- return stack.isEmpty();
- }
Python:
- class Solution:
- # @return a boolean
- def isValid(self, s):
- stack = []
- dict = {"]":"[", "}":"{", ")":"("}
- for char in s:
- if char in dict.values():
- stack.append(char)
- elif char in dict.keys():
- if stack == [] or dict[char] != stack.pop():
- return False
- else:
- return False
- return stack == []
Python: Time: O(n), Space: O(n)
- class Solution:
- def isValid(self, s):
- stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
- for parenthese in s:
- if parenthese in lookup: # Cannot use if lookup[parenthese]: KeyError
- stack.append(parenthese)
- elif len(stack) == 0 or lookup[stack.pop()] != parenthese: # Cannot use not stack
- return False
- return len(stack) == 0
Python: wo
- class Solution(object):
- def isValid(self, s):
- """
- :type s: str
- :rtype: bool
- """
- stack = []
- m = {'(': ')', '[': ']', '{': '}'}
- n = [')', ']', '}']
- for i in s:
- if i in m:
- stack.append(i)
- elif i in n and stack:
- if m[stack.pop()] != i:
- return False
- else:
- return False
- return len(stack) == 0
C++:
- class Solution {
- public:
- bool isValid(string s) {
- stack<char> parentheses;
- 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();
- }
- };
类似题目:
[LeetCode] 22. Generate Parentheses
[LeetCode] 32. Longest Valid Parentheses
[LeetCode] 241. Different Ways to Add Parentheses
[LeetCode] 301. Remove Invalid Parentheses
All LeetCode Questions List 题目汇总
[LeetCode] 20. Valid Parentheses 合法括号的更多相关文章
- [LeetCode] 20. Valid Parentheses 验证括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- [leetcode]20. Valid Parentheses有效括号序列
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- 【LeetCode】Valid Parentheses合法括号
给定一个仅包含 '('.')'.'{'.'}'.'['.']'的字符串,确定输入的字符串是否合法. e.g. "()"."()[]{}"."[()]( ...
- LeetCode 20 Valid Parentheses (括号匹配问题)
题目链接 https://leetcode.com/problems/valid-parentheses/?tab=Description Problem: 括号匹配问题. 使用栈,先进后出! ...
- leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、
20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']', de ...
- leetcode 20 Valid Parentheses 括号匹配
Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input ...
- [LeetCode]20. Valid Parentheses有效的括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- leetcode 20 Valid Parentheses 有效的括号
描述: 给定一些列括号,判断其有效性,即左括号有对应的有括号,括号种类只为小,中,大括号. 解决: 用栈. bool isValid(string s) { stack<char> st; ...
随机推荐
- python写入excel(方式1)
import xlsxwriter li=["张三","李四","王五","周六","王琪",&qu ...
- EntityFramework6 学习笔记(二)
使用EF对数据库进行操作,整个过程就像操作数组一样,我们只管修改或向集合中添加值,最后通知EF保存修改后的结果就可以了. 准备工作 为了演示,我在数据库中建了两张表.class表用于表示班级,clas ...
- JPA注解开发
JPA注解开发 jpa是sun公司的一个ORM规范,只有接口和注解,没有具体实现. jpa是EJB3中的. 单表常用注解 书写注解,并配置 @Entity @Table(name = "c_ ...
- Java静态static关键字
static关键字既可以修饰成员变量,也可以修改成员方法,修饰的成员变量和成员方法可以直接通过类名调用,也可以通过对象调用(其实即使是通过对象调用,也会被翻译成类名调用),建议通过类名调用. 成员方法 ...
- 看图轻松理解数据结构与算法系列(NoSQL存储-LSM树) - 全文
<看图轻松理解数据结构和算法>,主要使用图片来描述常见的数据结构和算法,轻松阅读并理解掌握.本系列包括各种堆.各种队列.各种列表.各种树.各种图.各种排序等等几十篇的样子. 关于LSM树 ...
- ssh集成
导入pom依赖 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w ...
- CF888G 【Xor-MST】
妙妙题-- 看到\(MST\),想到\(Kruskal\),看到异或,想到\(Trie\) 首先我们模拟一下\(Kruskal\)的流程:找到最小边,如果联通就忽略,未联通就加边 我们把所有点权值加入 ...
- SQL基础-子查询&EXISTS&UNION
一.子查询 1.使用子查询作为计算字段 子查询:嵌套在其他查询中的查询 现在有两个表,student表和teacher表 创建teacher表,并插入数据: CREATE TABLE `teacher ...
- SQL基础-过滤数据
一.过滤数据 1.使用WHERE子句 过滤数据:关键字WHERE SELECT 字段列表 FROM 表名 WHERE 过滤条件; 过滤条件一般由要过滤的字段.操作符.限定值三部分组成: 如: SELE ...
- Web前端开发工具和环境清单
初级 浏览器 Google Chrome 75.0.3770.100www.google.cn/intl/zh-CN/chrome初级 移动端模拟器 Genymotion 6.0.6www.genym ...