问题:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']',

determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

官方难度:

Easy

翻译:

给定一个字符串,仅包含字符:‘(’,‘)’,‘[’,‘]’,‘{’,‘}’。判断给定的字符串是不是一个合理的括号形式。括号必须顺序正确,诸如:“()”和“()[]{}”都是合理的,但是“(]”和“([)]”是不合理的。

  1. 首先判断字符串长度为0的特殊情况,返回true。
  2. 奇数长度的字符串,直接返回false。
  3. 定义2个字典方法,一个确定括号的方向,一个确定括号的级别。
  4. 这里特殊提一下,最初我认为类似“({})”不是合理的形式,但是提交时发现题目是允许这种形式的。
  5. 开始遍历字符串,维护一个左括号的集合。当遍历到左括号时,将这个字符加入集合;遍历到右括号时,首先判断左括号集合大小是否为0,若是,则返回false。然后比对左括号集合的最后一个元素与当前字符的括号级别和方向。
  6. 循环结束之后,若左括号集合大小不为0,返回false。
  7. 最后注意入参检查。

解题代码:

     public static boolean isValid(String str) {
if (str == null) {
throw new IllegalArgumentException("Input error");
}
// 0长度特殊处理
if (str.length() == 0) {
return true;
}
// 长度为奇数可以直接判断false
if (str.length() % 2 == 1) {
return false;
}
char[] array = str.toCharArray();
// 维护左括号的集合
List<Character> leftList = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (getDirection(array[i]) == 1) {
// 左括号处理
leftList.add(array[i]);
} else if (getDirection(array[i]) == -1) {
// 右括号处理
if (leftList.size() == 0) {
return false;
} else {
// 题目认为"({})"也是合理的形式
Character last = leftList.get(leftList.size() - 1);
if (getDirection(last) == -getDirection(array[i]) && getLevel(last) == getLevel(array[i])) {
leftList.remove(leftList.size() - 1);
} else {
return false;
}
}
} else {
throw new IllegalArgumentException("Input error");
}
}
// 循环结束之后判断leftList是否还有剩余
if (leftList.size() != 0) {
return false;
}
return true;
} // 括号级别
private static int getLevel(Character c) {
switch (c) {
case '{':
case '}':
return 3;
case '[':
case ']':
return 2;
case '(':
case ')':
return 1;
default:
return 0;
}
} // 括号方向
private static int getDirection(Character c) {
switch (c) {
case '{':
case '[':
case '(':
return 1;
case '}':
case ']':
case ')':
return -1;
default:
return 0;
}
}

isValid

相关链接:

https://leetcode.com/problems/valid-parentheses/

https://github.com/Gerrard-Feng/LeetCode/blob/master/LeetCode/src/com/gerrard/algorithm/easy/Q020.java

PS:如有不正确或提高效率的方法,欢迎留言,谢谢!

No.020:Valid Parentheses的更多相关文章

  1. LeetCode之“动态规划”:Valid Parentheses && Longest Valid Parentheses

    1. Valid Parentheses 题目链接 题目要求: Given a string containing just the characters '(', ')', '{', '}', '[ ...

  2. LeetCode OJ:Valid Parentheses(有效括号)

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  3. LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  4. LeetCode第[20]题(Java):Valid Parentheses

    题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...

  5. [LeetCode 题解]: Valid Parentheses

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  6. leetcode题解:Valid Parentheses(栈的应用-括号匹配)

    题目: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  7. leetcode解题报告(7):Valid Parentheses

    描述 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the i ...

  8. leetcode:Valid Parentheses

    括号匹配 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  9. LeetCode 020 Valid Parentheses

    题目描述:Valid Parentheses Given a string containing just the characters '(', ')', '{', '}', '[' and ']' ...

随机推荐

  1. Atitit  rgb yuv  hsv HSL 模式和 HSV(HSB) 图像色彩空间的区别

    Atitit  rgb yuv  hsv HSL 模式和 HSV(HSB) 图像色彩空间的区别 1.1. 色彩的三要素 -- 色相.明度.纯度1 1.2. YUV三个字母中,其中"Y&quo ...

  2. iOS----Asset Catalog的用法

    文/余书懿(简书作者)原文链接:http://www.jianshu.com/p/7aa06ce22a7b著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 引言 Asset Catalo ...

  3. jquery.validate 基础

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. 简述移动端IM开发的那些坑:架构设计、通信协议和客户端

    1.前言 有过移动端开发经历的开发者都深有体会:移动端IM的开发,与传统PC端IM有很大的不同,尤其无线网络的不可靠性.移动端硬件设备资源的有限性等问题,导致一个完整的移动端IM架构设计和实现都充满着 ...

  5. dubbo+zookeeper简单环境搭建

    dubbo+zoopeeper例子 [TOC] 标签(空格分隔): 分布式 dubbo dubbo相关 dubbo是目前国内比较流行的一种分布式服务治理方案.还有一种就是esb了.一般采用的是基于Ap ...

  6. Android实现下滑和上滑事件

    做过开发的对于下滑刷新与上滑加载都一定不陌生,因为我们在很多时候都会使用到,那对对于这个效果如何实现呢?相信难道过很多小伙伴,今天我就带领大家一道通过第三方组件快速完成上述效果的实现,保准每位小伙伴都 ...

  7. Node出错导致运行崩溃的解决方案

    许多人都有这样一种映像,NodeJS比较快: 但是因为其是单线程,所以它不稳定,有点不安全,不适合处理复杂业务: 它比较适合对并发要求比较高,而且简单的业务场景. 在Express的作者的TJ Hol ...

  8. mysql命令详解

    mysqld.exe 和 mysql.exe 有什么区别? mysqld.exe 是MySQL后台程序(即MySQL服务器).要想使用客户端程序,该程序必须运行,因为客户端通过连接服务器来访问数据库. ...

  9. ListView:The content of the adapter has changed but ListView did not receive a notification终极解决方法

    使用ListView时遇到如下的异常信息: 10-26 18:30:45.085: E/AndroidRuntime(7323): java.lang.IllegalStateException: T ...

  10. Azure REST API (2) Azure Storage

    <Windows Azure Platform 系列文章目录> 注意:本文适用于国内由世纪互联运维的Azure China. 本文将会介绍如何使用REST API来直接访问Storage ...