【算法】LeetCode算法题-Valid Parentheses
这是悦乐书的第147次更新,第149篇原创
01 看题和准备
今天介绍的是LeetCode算法题中Easy级别的第6题(顺位题号是20),给定一个只包含字符'(',')','{','}','['和']'的字符串,确定输入字符串是否有效。输入的字符串必须使用相同类型的括号关闭左括号,并且以正确的顺序关闭左括号。如果输入空串,返回true。例如:
输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "([)]"
输出: false
输入: "{[]}"
输出: true
本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。
02 第一种解法
利用字符串的替换方法。左括号和右括号必须一起出现,无论其里层还是外层有多少层,如"{()}","()"的外面有一层"{}",或者"{}"的里层是"()",将里面的"()"替换为空串,剩下"{}"再替换为空串,最后为空串,返回true。
public boolean isValid(String s) {
boolean flag = false;
if (s.isEmpty()) {
return true;
}
String s2 = s;
for (int i=0; i<s.length()/2; i++) {
s2 = s2.replaceAll("\\(\\)", "");
s2 = s2.replaceAll("\\{\\}", "");
s2 = s2.replaceAll("\\[\\]", "");
if (s2.length() == 0) {
return true;
}
}
return flag;
}
03 第二种解法
利用栈后进先出的特点。将左括号开头的字符依次存入栈中,遇到右括号时,从栈中取出进栈的数据,如果是一对左右括号,继续循环,反之返回false。
字符串"{()}",将其拆分为四个字符'{','(',')','}',第1次循环进栈字符是'{',第2次循环进栈字符是'(',第三次循环遇到右括号')',从栈中取出数据'(',判断是否为一对。依次往后循环判断。
public boolean isValid2(String s) {
Stack<Character> pare_stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch(c) {
case '(':
case '[':
case '{':
pare_stack.push(c);
break;
case ')' :
if (pare_stack.isEmpty()) {
return false;
} else {
if (pare_stack.pop() == '(') {
break;
} else {
return false;
}
}
case ']' :
if (pare_stack.isEmpty()) {
return false;
} else {
if (pare_stack.pop() == '[') {
break;
} else {
return false;
}
}
case '}' :
if (pare_stack.isEmpty()) {
return false;
} else {
if (pare_stack.pop() == '{') {
break;
} else {
return false;
}
}
}
}
return pare_stack.isEmpty();
}
04 第三种解法
利用数组。遇到左括号,将右括号放进数组;遇到右括号,取数组最后一位匹配,匹配上则删除数组最后一位元素继续循环,匹配不上则返回false。
public boolean isValid3(String s) {
List<String> nextClose = new ArrayList<>();
if (s.length() == 0) {
return true;
}
if (")]}".indexOf(s.charAt(0)) != -1) {
return false;
}
for (int i = 0; i < s.length(); i++) {
try {
switch (s.charAt(i)) {
case '(':
nextClose.add(")");
break;
case '[':
nextClose.add("]");
break;
case '{':
nextClose.add("}");
break;
case ')':
if (nextClose.get(nextClose.size() - 1) != ")") {
return false;
} else {
nextClose.remove(nextClose.size() - 1);
}
break;
case ']':
if (nextClose.get(nextClose.size() - 1) != "]") {
return false;
} else {
nextClose.remove(nextClose.size() - 1);
}
break;
case '}':
if (nextClose.get(nextClose.size() - 1) != "}") {
return false;
} else {
nextClose.remove(nextClose.size() - 1);
}
break;
}
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
return nextClose.size() == 0;
}
05 小结
此题解法远不止上面这三种,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

本文首发于我的个人公众号:悦乐书,转载请注明出处!
【算法】LeetCode算法题-Valid Parentheses的更多相关文章
- 乘风破浪:LeetCode真题_022_Generate Parentheses
乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...
- 乘风破浪:LeetCode真题_020_Valid Parentheses
乘风破浪:LeetCode真题_020_Valid Parentheses 一.前言 下面开始堆栈方面的问题了,堆栈的操作基本上有压栈,出栈,判断栈空等等,虽然很简单,但是非常有意义. 二.Valid ...
- [LeetCode] 032. Longest Valid Parentheses (Hard) (C++)
指数:[LeetCode] Leetcode 指标解释 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 032. Lon ...
- LeetCode 之 Longest Valid Parentheses(栈)
[问题描写叙述] Given a string containing just the characters '(' and ')', find the length of the longest v ...
- Java [leetcode 32]Longest Valid Parentheses
题目描述: Given a string containing just the characters '(' and ')', find the length of the longest vali ...
- [LeetCode] 32. Longest Valid Parentheses 最长有效括号
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- Java for LeetCode 032 Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
- [Leetcode][Python]20: Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...
- leetcode 32. Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...
随机推荐
- Go基础系列:Go中的方法
Go方法简介 Go中的struct结构类似于面向对象中的类.面向对象中,除了成员变量还有方法. Go中也有方法,它是一种特殊的函数,定义于struct之上(与struct关联.绑定),被称为struc ...
- tomcat开启自启动
linux方式 #!/bin/bash #chkconfig: #description: Starts and Stops the Tomcat daemon. #by benjamin ##### ...
- MySQL分页查询性能优化
当需要从数据库查询的表有上万条记录的时候,一次性查询所有结果会变得很慢,特别是随着数据量的增加特别明显,这时需要使用分页查询.对于数据库分页查询,也有很多种方法和优化的点.下面简单说一下我知道的一些方 ...
- springboot使用hibernate validator校验,Bean Validation校验
第一个地址:springboot使用hibernate validator校验,Bean Validation校验
- MyBatis:GeneratorConfig生成mapper以及pojo
首先我们需要导入相应的依赖 之后需要针对的配置一些数据 接着我们需要针对性的写配置文件,在根目录下写mybatis的主要配置文件 如上图我们配置了数据库连接.对应的一些pojo.mapper.java ...
- Netty实战八之引导
通过前面的学习,我们可能要考虑一个问题:如何将这些部分组织起来,成为一个可实际运行的应用程序呢? 答案是引导.简单来说,引导一个应用程序是指对它进行配置,并使它运行起来的过程——尽管该过程的具体细节可 ...
- idea项目git版本回退
idea项目git版本回退 一.查询提交历史 项目上右键,点击Git,点击Show History 二.复制版本号 我这里有两个测试的版本,我的当前版本是[二],所以我选择[一],右键,选择Copy ...
- 5.枚举和注解_EJ
第30条: 用enum代替int常量 枚举类型是指由一组固定的常量组成合法值得类型.例如一年中的季节,太阳系中的行星或一副牌中的花色.在开发中我们经常在类使用static final来定义一个int常 ...
- memcached 源码阅览 一
想要快速了解memcached内部原理么?那么赶紧离开本页,这会耽误您的时间. 不知时隔多少时间,今天受了些刺激,在码农路上开始犹豫起来,但是想想自己也没其他本身,就只好放下王者荣耀,重新看看技术内容 ...
- 一些你可能不熟悉的JS知识点总结
js代码暂时性死区 只要块级作用域存在let命令,它所声明的变量就“绑定”这个区域,不再受外部的影响.这么说可能有些抽象,举个例子: ? 1 2 3 4 5 var temp = 123; if(tr ...