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. jupyter notebook中导入其他ipynb文件中的代码

    %%capture %run "../Untitled Folder 3/2nn.ipynb" %%capture 抑制输出%run "../Untitled Folde ...

  2. Mybatis容易遇到的问题

    1.MyBatis中#和$的区别? 1.使用#的原理是?占位符,而$的原理为直接字符串拼接方式 2.$方式一般使用在写数据库中的固定字段时候才会使用例如表名或者列名(select * from use ...

  3. 项目Alpha冲刺(团队)-第十天冲刺

    格式描述 课程名称:软件工程1916|W(福州大学) 作业要求:项目Alpha冲刺(团队) 团队名称:为了交项目干杯 作业目标:描述第十天冲刺的项目进展.问题困难.心得体会 队员姓名与学号 队员学号 ...

  4. centos7中,mysql连接报错:1130 - Host ‘118.111.111.111’ is not allowed to connect to this MariaDB server

    客户端连接报错 这个问题是因为用户在数据库服务器中的mysql数据库中的user的表中没有权限. 解决步骤 1.连接服务器: mysql -u root -p 2.看当前所有数据库:show data ...

  5. java中异步调用注意

    Future接口是Java标准API的一部分,在java.util.concurrent包中.Future接口是Java线程Future模式的实现,可以来进行异步计算. 有了Future就可以进行三段 ...

  6. SparkSQL读写外部数据源-json文件的读写

    object JsonFileTest { def main(args: Array[String]): Unit = { val spark = SparkSession .builder() .m ...

  7. LeetCode(数据库)部门最高工资

    ), Salary int, DepartmentId int) )) Truncate table Employee ') ') ') ') Truncate table Department ', ...

  8. WinDbg常用命令系列---断点操作b*

    ba (Break on Access) ba命令设置处理器断点(通常称为数据断点,不太准确).此断点在访问指定内存时触发. 用户模式下 [~Thread] ba[ID] Access Size [O ...

  9. 微信小程序电影模板

    [外链图片转存失败(img-STw401rR-1565101469846)(https://upload-images.jianshu.io/upload_images/11158618-52efd0 ...

  10. 图解CRM(客户关系管理)全流程

    https://blog.csdn.net/lylmwt/article/details/84921432