这是悦乐书的第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的更多相关文章

  1. 乘风破浪:LeetCode真题_022_Generate Parentheses

    乘风破浪:LeetCode真题_022_Generate Parentheses 一.前言 关于括号的题目,我们已经遇到过了验证正确性的题目,现在让我们生成合法的括号列表,怎么办呢?想来想去还是递归比 ...

  2. 乘风破浪:LeetCode真题_020_Valid Parentheses

    乘风破浪:LeetCode真题_020_Valid Parentheses 一.前言 下面开始堆栈方面的问题了,堆栈的操作基本上有压栈,出栈,判断栈空等等,虽然很简单,但是非常有意义. 二.Valid ...

  3. [LeetCode] 032. Longest Valid Parentheses (Hard) (C++)

    指数:[LeetCode] Leetcode 指标解释 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 032. Lon ...

  4. LeetCode 之 Longest Valid Parentheses(栈)

    [问题描写叙述] Given a string containing just the characters '(' and ')', find the length of the longest v ...

  5. Java [leetcode 32]Longest Valid Parentheses

    题目描述: Given a string containing just the characters '(' and ')', find the length of the longest vali ...

  6. [LeetCode] 32. Longest Valid Parentheses 最长有效括号

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  7. Java for LeetCode 032 Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

  8. [Leetcode][Python]20: Valid Parentheses

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...

  9. leetcode 32. Longest Valid Parentheses

    Given a string containing just the characters '(' and ')', find the length of the longest valid (wel ...

随机推荐

  1. DNS工作原理

    一.简述dns DNS(domain name system)域名系统或者(domain named system)区域名称服务,分为正向与反向域名解析,适用C/S,端口路53/udp,53/tcp, ...

  2. OOP面向对象

    一:什么是面向过程 我们是怎么思考和解决上面的问题呢? 答案是:我们自己的思维一直按照步骤来处理这个问题,这是我们的常规思维,这就是所谓的面向过程POP编程   二:面向过程POP为什么转换为OOP ...

  3. 写一个ORM框架的第一步(Apache Commons DbUtils)

    新一次的内部提升开始了,如果您想写一个框架从Apache Commons DbUtils开始学习是一种不错的选择,我们先学习应用这个小“框架”再把源代码理解,然后写一个属于自己的ORM框架不是梦. 一 ...

  4. ls 指令的介绍

    每个文件在linux下面都会记录许多的时间参数, 其实是有三个主要的变动时间,那么三个时间的意义是什么呢? modification time (mtime) : 当该文件的“内容数据”变更时,就会更 ...

  5. c# 模拟网易足彩算法

    using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...

  6. 【Java每日一题】20170120

    20170119问题解析请点击今日问题下方的“[Java每日一题]20170120”查看(问题解析在公众号首发,公众号ID:weknow619) package Jan2017; import jav ...

  7. virtualbox中 清理磁盘

    1. 碎片整理 windows: 下载 sdelete 工具 执行命令: sdelete –z c:\ Linux: 执行如下命令: sudo dd if=/dev/zero of=/EMPTY bs ...

  8. java ee,包括js,html,jsp等等知识整合

    为了方便修改和后续的包装套路   首先用户访问的页面从web.xml找到 <welcome-file-list> <welcome-file>index.html</we ...

  9. Linux禁止ping以及开启ping的方法

    ---恢复内容开始--- Linux默认是允许Ping响应的,系统是否允许Ping由2个因素决定的:A.内核参数,B.防火墙,需要2个因素同时允许才能允许Ping,2个因素有任意一个禁Ping就无法P ...

  10. loj#6030. 「雅礼集训 2017 Day1」矩阵(贪心 构造)

    题意 链接 Sol 自己都不知道自己怎么做出来的系列 不难观察出几个性质: 最优策略一定是先把某一行弄黑,然后再用这一行去覆盖不是全黑的列 无解当且仅当无黑色.否则第一个黑色所在的行\(i\)可以先把 ...