20_有效的括号(Valid-Parentheses)

描述

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

示例 1:

输入: "()"
输出: true

示例 2:

输入: "()[]{}"
输出: true

示例 3:

输入: "(]"
输出: false

示例 4:

输入: "([)]"
输出: false

示例 5:

输入: "{[]}"
输出: true

解法

思路

遍历字符串的每个字符,如果字符是左半边的括号(即 ([ 或者{),将字符压入栈;如果字符是右半边括号(即 )] 或者 }),此时首先判断堆栈是否为空,如果栈为空,则该字符无法找到匹配的括号,返回 false,如果栈不为空,则弹出栈顶元素并与之比较,如果两个字符不相同,同样返回 false。最后,遍历完整个字符串后,还需要判断堆栈是否为空,如果为空,则是有效的括号,反之则为无效的括号。

Java 实现

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i=0; i<s.length(); i++) {
char c = s.charAt(i); if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.empty()) {
return false;
} char topChar = stack.pop();
if (c == ')' && topChar != '(') {
return false;
}
if (c == ']' && topChar != '[') {
return false;
}
if (c == '}' && topChar != '{') {
return false;
}
}
} return stack.isEmpty();
}
}

改进版:

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(') {
stack.push(')');
} else if (c == '[') {
stack.push(']');
} else if (c == '{') {
stack.push('}');
} else if (stack.isEmpty() || c != stack.pop()) {
return false;
}
}
return stack.isEmpty();
}
}

Python 实现

实现1:

class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = list()
for si in s:
if si == '(':
stack.append(')')
elif si == '[':
stack.append(']')
elif si == '{':
stack.append('}')
elif len(stack) == 0 or si != stack.pop():
return False
return len(stack) == 0

实现 2(借助字典):

class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = list()
dict = {'(': ')', '[': ']', '{': '}'}
for c in s:
if c in dict.keys():
stack.append(dict[c])
elif c in dict.values():
if len(stack) == 0 or c != stack.pop():
return False
else:
False
return len(stack) == 0

复杂度分析

  • 时间复杂度:\(O(n)\),其中 \(n\) 表示字符串的长度
  • 空间复杂度:\(O(n)\),最坏的情况下,堆栈需要存放字符串的所有字符

【LeetCode题解】20_有效的括号(Valid-Parentheses)的更多相关文章

  1. LeetCode 20:有效的括号 Valid Parentheses

    给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. Given a string containing just the characters '(', ' ...

  2. LeetCode 20. 有效的括号(Valid Parentheses)

    20. 有效的括号 20. Valid Parentheses 题目描述 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须 ...

  3. 【leetcode刷题笔记】Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  4. 【LeetCode每天一题】Longest Valid Parentheses(最长有效括弧)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  5. LeetCode 1249. Minimum Remove to Make Valid Parentheses

    原题链接在这里:https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/ 题目: Given a string s ...

  6. [Swift]LeetCode20. 有效的括号 | Valid Parentheses

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

  7. [LeetCode]题解(python):022-Generate Parentheses

    题目来源: https://leetcode.com/problems/generate-parentheses/ 题意分析: 题目输入一个整型n,输出n对小括号配对的所有可能性.比如说,如果输入3, ...

  8. [LeetCode]题解(python):020-Valid Parentheses

    题目来源: https://leetcode.com/problems/valid-parentheses/ 题意分析: 这道题输入一段只包括括号的字符串,判断这个字符串是否已经配对.配对的规则是,每 ...

  9. LeetCode第[20]题(Java):Valid Parentheses

    题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...

  10. LeetCode题解-20.有效的括号

    题目 给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭合. 示例 ...

随机推荐

  1. [python01] python列表,元组对比Erlang的区别总结

    数据结构是通过某种方式组织在一起的数据元素的集合,这些数据元素可以是数字,字符,甚至可以是其他的数据结构. python最基本的数据结构是sequence(序列):6种内建的序列:列表,元组,字符串, ...

  2. LOJ121 【离线可过】动态图连通性

    题目链接:戳我 [线段树分治版本代码] 这里面的线段树是时间线段树,每一个节点都要开一个vector,记录当前时间区间中存在的边的标号qwq #include<iostream> #inc ...

  3. 云架构和openstack的思考

    原文链接: http://ifeve.com/cloud-architecture-openstack/ 作者:罗立树 最近在负责公司内部私有云的建设,一直在思考怎么搞云计算,怎么才能够把云架构设计得 ...

  4. 486. Predict the Winner

    Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from eith ...

  5. CentOS7安装weblogic集群思路梳理

    以前经常用weblogic集群,但是却没有仔细想过要实现它.这不,前两天成功安装了weblogic集群,现在将其思路整理下.防止日后自己忘掉了. 一.安装weblogic10.3.6 1. 在官网下载 ...

  6. 线程池(Linux实现)

    讨论QQ群:135202158 本文技术参考了sourceforge项目c thread pool,链接:http://sourceforge.net/projects/cthpool/ 线程池如上一 ...

  7. Vim 中的持久撤消

    Vim中的持久撤消 阅读文本大约需要俩分钟. 在 Vim 中像其他文本编辑器一样,你可以在当前会话中执行 "撤销/重做" .当一旦会话关闭,则你需要重新打开一个新文章,运行撤销将不 ...

  8. 49.RocketMQ 双主搭建(本文非EamonSec原创)

    声明:本文非EamonSec原创,copy自网上下载的某个个文件 1.RocketMQ介绍 1.1. 简介 RocketMQ 是一款分布式.队列模型的消息中间件,具有以下特点: 能够保证严格的消息顺序 ...

  9. 题目1002:Grading(简单判断)

    问题来源 http://ac.jobdu.com/problem.php?pid=1002 问题描述 题目背景为高考试卷批改打分制度.对于每一道题,至少需要两位评审老师进行打分, 当两个老师的打分结果 ...

  10. JDK源码分析(10) ConcurrentLinkedQueue

    概述 我们要实现一个线程安全的队列有两种实现方法一种是使用阻塞算法,另一种是使用非阻塞算法.使用阻塞算法的队列可以用一个锁(入队和出队用同一把锁)或两个锁(入队和出队用不同的锁)等方式来实现,而非阻塞 ...