【算法】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 ...
随机推荐
- ife 零基础学院 day 2
第二天:给自己做一个在线简历吧 最后的验证,提出了几个问题,尝试解答一下 HTML是什么,HTML5是什么 HTML的定义摘抄自w3school的HTML 简介 HTML 是用来描述网页的一种语言. ...
- 第一册:lesson seventeen。
原文:How do ;you do? A:Come and meet our employees,Mr.B. B:Thank you Mr.A. A:This is ...and this is .. ...
- IDEA更换主题
更换IDEA主题只需要3步 1. 下载主题 在主题网站上IDEA Color Themes 上浏览喜欢的主题并下载该主题.(如果网址有变更,google IDEA themes即可.) 2. 导入主 ...
- Android Studio 基础控件使用
TextView android:gravity="center" //文字对其方式 top bottom left right center android:textColor= ...
- Java高并发--安全发布对象
Java高并发--安全发布对象 主要是学习慕课网实战视频<Java并发编程入门与高并发面试>的笔记 发布对像:使一个对象能够被当前范围之外的对象使用. 对象逸出:一种错误的发布.当一个对象 ...
- Java基础IO流(三)字符流
字符流: 文本和文本文件: java的文本(char)是16位无符号整数,是字符的unicode编码(双字节编码)文件是byte byte byte....的数据序列,而文本文件是文本(char)序列 ...
- java集合框架-List集合ArrayList和LinkedList详解
List 集合源码剖析 ✅ ArrayList 底层是基于数组,(数组在内存中分配连续的内存空间)是对数组的升级,长度是动态的. 数组默认长度是10,当添加数据超越当前数组长度时,就会进行扩容,扩容长 ...
- 1; XHTML 基本知识
万维网是我们这个时代最重要的信息传播手段.几乎任何人都可以创建自己的网站,然后把它发布在因特网上.一些网页属于企业,提供销售服务:另一些网页属于个人,用来分享信息.你可以自己决定网页的内容和风格.所有 ...
- angular 拼接html 事件无效
主要是要引用$compile方法
- 关于微信小程序<radio-group>布局排列
微信小程序更新以后今天<radio>全部变成垂直排列了,布局乱了. 一开始尝试给外层<view>添加display:flex;flex-direction:row:未果. 后来 ...