【算法】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 ...
随机推荐
- 南大算法设计与分析课程OJ答案代码(5)--割点与桥和任务调度问题
问题 A: 割点与桥 时间限制: 1 Sec 内存限制: 5 MB提交: 475 解决: 34提交 状态 算法问答 题目描述 给出一个无向连通图,找到所有的割点和桥 输入 第一行:点的个数,如果点 ...
- [转]Node.JS使用Sequelize操作MySQL
Sequelize官方文档 https://sequelize.readthedocs.io/en/latest/ 本文转自:https://www.jianshu.com/p/797e10fe23 ...
- [转]Docker版本变化和新版安装
本文转自:http://www.cnblogs.com/Peter2014/p/7704306.html Docker从1.13版本之后采用时间线的方式作为版本号,分为社区版CE和企业版EE. 社区版 ...
- 建立多页面vue.js项目
介绍 根据需求,我们希望建立一个多页面的vue.js项目,如何改造单页面vue.js项目为多页面项目?跟着我的步伐看下去吧. 1.创建单页面vue.js项目 简单的记录一下创建步骤: --安装cnpm ...
- WPF 绕圈进度条(二)
一 以前的方案 以前写过一个圆点绕圈的进度条,根据参数圆点个数和参数每次旋转角度,主要是在cs文件中动态添加圆点,通过后台定时器,动态设置角度后用正弦余弦计算(x,y)的位置. 此方案优点:动态添加L ...
- .net 公共基础类
using WL.Infrastructure.Http; using System; using System.Collections.Generic; using System.IO; using ...
- PS换脸操作
1,使用套索工具抠出人的五官. 2,Ctrl+C复制黏贴到另一张头像中,调节透明度50%,与需要换脸的头像的眼睛,嘴巴,鼻子重合,透明度回归100%. 3,为了不该变原图,需要新建一张原图. 4,在抠 ...
- vim编辑器的设置
1.vim编辑器设置分为两种设置,临时设置和永久设置 2.临时设置开启和关闭高亮模式(目前高亮模式是开启的) etc/ man.config vim man.config 在文本编辑器中命令行模式下输 ...
- vue-cli创建的项目的目录结构及说明
转自:http://blog.csdn.net/qq_34543438/article/details/72868546?locationNum=3&fps=1 一. ├── build ...
- JS实现数组去重方法整理
前言 我们先来看下面的例子,当然来源与网络,地址<删除数组中多个不连续的数组元素的正确姿势> 我们现在将数组中所有的‘ a’ 元素删除: var arr = ['a', 'a', 'b', ...