【算法】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 ...
随机推荐
- Hyperledger Fabric之模型
本文主要介绍Hyperledger Fabric的主要设计特点,为了满足功能丰富.可定制.企业化区块链解决方案. Assets - 资产定义,使得任何形式的资产,从食物到汽车到货币都可以进行自由的交换 ...
- vue_drf之多级过滤、排序、分页
一.前端代码 1,父组件free_course.vue <template> <div id="free_course"> <el-container ...
- Maven私服 Nexus使用一例
一.背景 本次搭建Nexus的私服是为了解决两件事 1.公司网络限制,部分项目组同事无法直接访问互联网,不能直接下载一些依赖的jar文件; 2.一些独立的jar无法通过Maven添加依赖的方式引入到项 ...
- Android开发过程中的坑及解决方法收录(一)
之前使用了Android Studio的插件直接为button绑定了监听器,并实现onClick方法(我的onClick方法无论点击哪一个都是要实现setcontentview这个方法设置layout ...
- redux 入门
背景: 在react中使用redux 重点:不要滥用redux,如果你的页面非常简单,没有 那么多的互动,那么就不要使用redux,反而会增加项目的复杂性. 如果你有以下情况,则可以考虑使用redux ...
- javascript模块化编程-立即执行函数(IIFE)
IIFE 全拼Imdiately Invoked Function Expression,立即执行的函数表达式. 语法 var module1 = (function(){ var _count = ...
- viewer.js 视图预览demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...
- input 属性为 number,maxlength不起作用如何解决?
<input type="text" maxlength="5" /> 效果ok, 当 <input type="number ...
- python之匿名函数以及在内置函数中的使用
一. 匿名函数 Python使用 lambda 来创建匿名函数.所谓匿名函数,它与用 def 关键字定义的函数相比,没有函数名称. 1.1 匿名函数定义及特点 语法: lambda [para1, p ...
- js判断当前内容是否为空
function isValue(o) { return (this.isObject(o) || this.isString(o) || this.isNumber(o) || this.isBoo ...