问题:

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.软件中见算法 程序设计五大种类算法

    Atitit.软件中见算法 程序设计五大种类算法 1. 算法的定义1 2. 算法的复杂度1 2.1. Algo cate2 3. 分治法2 4. 动态规划法2 5. 贪心算法3 6. 回溯法3 7. ...

  2. C#并行编程-PLINQ:声明式数据并行

    目录 C#并行编程-相关概念 C#并行编程-Parallel C#并行编程-Task C#并行编程-并发集合 C#并行编程-线程同步原语 C#并行编程-PLINQ:声明式数据并行 背景 通过LINQ可 ...

  3. draggable属性设置元素是否可拖动。

    设置标签属性draggable="true"将一个标签内的元素拖动到另外一个标签进行显示: <!DOCTYPE HTML> <html> <head& ...

  4. [ASP.net MVC] 将HTML转成PDF档案,使用iTextSharp套件的XMLWorkerHelper (附上解决显示中文问题)

    原文:[ASP.net MVC] 将HTML转成PDF档案,使用iTextSharp套件的XMLWorkerHelper (附上解决显示中文问题) [ASP.net MVC] 将HTML转成PDF档案 ...

  5. KnockoutJS 3.X API 第五章 高级应用(3) 虚拟元素绑定

    注意:这是一种高级技术,通常仅在创建可重用绑定的库时使用. 这不是你通常需要做的时候使用Knockout构建应用程序. Knockout的控制流绑定(例如,if和foreach)不仅可以应用于常规DO ...

  6. 优化与扩展Mybatis的SqlMapper解析

    接上一篇博文,这一篇来讲述怎么实现SchemaSqlMapperParserDelegate——解析SqlMapper配置文件. 要想实现SqlMapper文件的解析,还需要仔细分析一下mybatis ...

  7. Android_文件存储

    因为项目的需求,想实现一个指导使用的欢迎页效果,通过在网上的询问,给的一种解决办法是通过SharedPreferences文件存储方式来实现,具体的实现类似于通过第一次取得SharedPreferen ...

  8. Linux RHCS 基础维护命令

    本文只是介绍Linux RHCS最基本的一些维护命令,属于DBA应该了解的层面. 查看集群状态 集群正常启动 集群正常关闭 查看服务是否关闭开机启动 1. 查看集群状态 clustat cman_to ...

  9. webpack打包压缩工具的使用方法

    具体使用方法参考来源http://www.cnblogs.com/Leo_wl/p/4793722.html 必须注意的地方: 一.webpack在nodejs环境下运行 二,每个目录下都必须有一个w ...

  10. Android Studio快捷键每日一练(5)

    原文地址:http://www.developerphil.com/android-studio-tips-of-the-day-roundup-5/ 42.Enter键和Tab键补全 快捷键:Ent ...