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. Solr查询query效果对比

    q条件 默认分词(org.apache.solr.analysis.TokenizerChain) "parsedquery" IK分词(org.wltea.analyzer.lu ...

  2. lucene整理3 -- 排序、过滤、分词器

    1.    排序 1.1. Sort类 public Sort() public Sort(String field) public Sort(String field,Boolean reverse ...

  3. VUE 学习笔记 四 计算属性和监听器

    1.计算属性 对于任何复杂逻辑,你都应当使用计算属性 <div id="example"> <p>Original message: "{{ me ...

  4. byte[] 数组和字符串的转换,与byte[] 数组和int类型的之间的转化

    我们先来看看byte bool  int ushort  等的定义 首先时byte[]数组与string之间的转换 string 转换位byte[] 数组 string str = "1-1 ...

  5. 日笔记--C# 从数据库取表格到DataGridView---json传输

    只作为个人学习笔记. class OpData { // 创建一个和客户端通信的套接字 Socket socketwatch = null; //连接Access字符串 string strCon; ...

  6. java学习笔记—第三方操作数据库包专门接收DataSource-dbutils (30)

    Dbutils 操作数据第三方包.依赖数据源DataSource(DBCP|C3p0). QueryRunner – 接收DataSource|Connection,查询数据删除修改操作.返回结果. ...

  7. 【bug】—— H5页面在 ios 端滑动不流畅的问题

    IOS系统的惯性滑动效果非常6,但是当我们对div加overflow-y:auto;后是不会出这个效果的,滑动的时候会感觉很生涩.怎么办? 方案一: 在滚动容器内加-webkit-overflow-s ...

  8. [转] 测试环境下将centos6.8升级到centos7的操作记录

    1)查看升级前的版本信息 lsb_release -a LSB Version: :base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noa ...

  9. django model改变后,同步数据库

    在使用django进行开发时,往往需要根据不同的需求对model进行更改.而这时候,python manage.py syncdb就不好使了. 目前有个很好的工具,是south,这个是专门用来更改mo ...

  10. mybatis的执行流程

    1.SqlSessionFactoryBuilder与SqlSessionFactory 我们一般在使用mybatis是都会通过new SqlSessionFactoryBuilder.build(. ...