问题:

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. 本地MVC项目发布到IIS服务器

    0瞎扯 朋友们有时候我们写个一个web程序只能使用卡西尼服务器调试,下面我教大家发布到IIS服务器上(包括本地ISS7.5和远程服务器 IIS) 1.VS发布 a.点击web项目->发布

  2. Topology and Geometry in OpenCascade-Face

    Topology and Geometry in OpenCascade-Face eryar@163.com 摘要Abstract:本文简要介绍了几何造型中的边界表示法(BRep),并结合程序说明O ...

  3. 程序是如何执行的(一)a=a+1

    本文链接:http://www.orlion.ml/35/ 一.概述 1.计算机中有两个主要的核心部件:CPU和内存,其中CPU负责运算而内存负责存储程序和相关的变量,每一条程序语句和变量都在内存中有 ...

  4. sys.dm_db_wait_stats

    sys.dm_db_wait_stats 返回在操作期间执行的线程所遇到的所有等待的相关信息. 可以使用此聚合视图来诊断 Azure SQL Database 以及特定查询和批处理的性能问题. 执行查 ...

  5. java接口中多继承的问题

    java中支撑多继承吗? 支持->接口啊 为什么接口支持多继承呢?因为接口中没有方法体!即使可能两个接口中有一样的抽象方法,但是 只会调用子类中覆盖该同样抽象方法的具体方法!不会引起调用的歧义! ...

  6. Docker如何为企业产生价值?

    一个 IT 系统大致可以分为: 应用程序 运行时平台(bin/framework/lib) 操作系统 硬件(基础设施) 开发人员的主要工作是应用程序的编码.构建.测试和发布,涉及应用程序和运行时平台这 ...

  7. 转载--linux filesystem structures

    In this article, let us review the Linux filesystem structures and understand the meaning of individ ...

  8. MySQL:基础—数据分组

    MySQL:基础-数据分组 1.为什么要分组: 比如一个表中有多条订单记录,如上图,每条记录对应着一个商品,现在我要查询 每个商品被订购的单数 准备出货?也就是找到每个商品被订购的数量. 如果只找一个 ...

  9. Gephi可视化(一)——使用Gephi Toolkit创建Gephi应用

    在Prefuse上摸打滚爬了一段时间,发现其和蔼可亲,容易上手.但是每每在打开gephi,导入数据再运行时,总还是在心里暗自赞叹gephi的绚烂之极,无与匹敌,当然,gephi也有自己的缺陷,但是ge ...

  10. Fort.js – 时尚、现代的表单填写进度提示效果

    Fort.js 是一款用于时尚.现代的表单填写进度提示效果的 JavaScript 库,你需要做的就是添加表单,剩下的任务就交给 Fort.js 算法了,使用非常简单.提供了Default.Gradi ...