Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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 合法括号的更多相关文章

  1. [LeetCode] 20. Valid Parentheses 验证括号

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  2. [leetcode]20. Valid Parentheses有效括号序列

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  3. 【LeetCode】Valid Parentheses合法括号

    给定一个仅包含 '('.')'.'{'.'}'.'['.']'的字符串,确定输入的字符串是否合法. e.g. "()"."()[]{}"."[()]( ...

  4. LeetCode 20 Valid Parentheses (括号匹配问题)

    题目链接 https://leetcode.com/problems/valid-parentheses/?tab=Description   Problem: 括号匹配问题. 使用栈,先进后出!   ...

  5. leetcode 20. Valid Parentheses 、32. Longest Valid Parentheses 、

    20. Valid Parentheses 错误解法: "[])"就会报错,没考虑到出现')'.']'.'}'时,stack为空的情况,这种情况也无法匹配 class Soluti ...

  6. leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法

    Valid Parentheses  Given a string containing just the characters '(', ')', '{', '}', '[' and ']', de ...

  7. leetcode 20 Valid Parentheses 括号匹配

    Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input ...

  8. [LeetCode]20. Valid Parentheses有效的括号

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  9. leetcode 20 Valid Parentheses 有效的括号

    描述: 给定一些列括号,判断其有效性,即左括号有对应的有括号,括号种类只为小,中,大括号. 解决: 用栈. bool isValid(string s) { stack<char> st; ...

随机推荐

  1. spring cloud (七) Config server基于svn配置

    1 pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="h ...

  2. ThinkPHP模板之二

    模板布局及变量比较,循环. controller <?php /** * Created by PhpStorm. * User: Sahara * Date: 2019/6/23 * Time ...

  3. Please, another Queries on Array?(Codeforces Round #538 (Div. 2)F+线段树+欧拉函数+bitset)

    题目链接 传送门 题面 思路 设\(x=\prod\limits_{i=l}^{r}a_i\)=\(\prod\limits_{i=1}^{n}p_i^{c_i}\) 由欧拉函数是积性函数得: \[ ...

  4. Redis.Memcache和MongoDB区别?

    Memcached的优势: Memcached可以利用多核优势,单吞吐量极高,可以达到几十万QPS(取决于Key.value的字节大小以及服务器硬件性能,日常环境中QPS高峰大约在4-6w左右.)适用 ...

  5. Python开发应用-操作excel

    一. openpyxl读 95%的时间使用的是这个模块,目前excel处理的模块,只有这个还在维护 1.workBook workBook=openpyxl.load_workbook('path(. ...

  6. Djiango-建立模型抽象基类

    创建一个抽象模型基类 ‘ 然后 ’base_model.py from django.db import models from datetime import date class BaseMode ...

  7. WebPack探索之路(1)

    1. 卸载全局的webpack npm ininstall webpack webpack-cli -g 其中安装webpack-cli 是可以让webpack在命令行中执行.在webpack4.0中 ...

  8. Windows 2008R2 定时备份PostgreSQL 11.6及还原操作

    PostgreSQL 自动备份,并删除10天前的备份文件. 第一步,创建脚本,命名back.bat文件,可直接点击执行或者CMD执行此批处理命令. @ECHO OFF @setlocal enable ...

  9. mov offset和lea的区别

    mov offset和lea的区别  原文地址:https://www.cnblogs.com/fanzi2009/archive/2011/11/29/2267725.html 全局变量取地址用mo ...

  10. windowns server 2008 r2 AD桌面文件重定向设置

    1.创建将要进行重定向的组(此处为chongdingxiangzu) 2.选择要重定向的用户,并将此用户加入到要重定向的组里 3.打开组策略管理,右击刚才用户所属的组织单位(OU)进行新建GPO(此处 ...