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. [Java]java内存及数据区

    Java运行时的数据区包括:(其中前两个是线程共享的) 1.方法区(Method Area) 存储已被虚拟机加载的类信息.常量.静态变量.即时编译器编译后的代码等数据 2.堆(Heap) 存放对象实例 ...

  2. 在VC++中执行VBS代码

    此代码来自https://blog.csdn.net/zhu2695/article/details/13770671 作者: zhu2695   时间:2013年10月31日 13:08:41 #i ...

  3. C# 键盘中的按键对应KeyValue

    首先先看一下什麼情況下需要對按鍵進行識別: KeyPress事件響應函數中,有KeyPressEventArgs, 對應於e.KeyChar; KeyDown事件響應中有KeyEventArgs 求取 ...

  4. 【文文殿下】【HAOI2008】硬币购物

    题目描述 硬币购物一共有4种硬币.面值分别为c1,c2,c3,c4.某人去商店买东西,去了tot次.每次带di枚ci硬币,买si的价值的东西.请问每次有多少种付款方法. 数据规模 di,s<=1 ...

  5. jzoj3717

    #include<bits/stdc++.h> using namespace std; extern int main2(void) __asm__ ("main2" ...

  6. fd - 更好的 find 命令

    欢迎关注我的公众号 spider-learn fd(https://github.com/sharkdp/fd) 是 find 命令的一个更现代的替换. 对比一下 查找名字含有某个字符的文件 OLD ...

  7. C++中指针运算

    1,指针可以和数字运算,指针+-整数,如, int num[] = {1,2,3,4,5,6,7,8}; int *p = num; p++; p--; p = p + 3; p = p -3; 数字 ...

  8. Dota2App--第三天

    一.要实现的功能 1.新特性页面 1.1.是否进入新特性界面的两种情况 1)第一次安装此APP,进入新特性界面 2)不是第一次安装,但是有版本更新,进入新特性界面 1.2.具体的代码实现 //0.版本 ...

  9. video.js 应用于网站需要视频的

    http://www.cnblogs.com/lechenging/p/3858181.html

  10. 小M的作物 最小割最大流

    题目描述 小M在MC里开辟了两块巨大的耕地A和B(你可以认为容量是无穷),现在,小P有n中作物的种子,每种作物的种子有1个(就是可以种一棵作物)(用1...n编号). 现在,第i种作物种植在A中种植可 ...