问题:

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 英文与中文与阿拉伯文的简化解决方案.docx

    atitit 英文与中文与阿拉伯文的简化解决方案.docx 1. 英文与中文与阿拉伯文的简化意义1 2. 简化的主要方法分类2 2.1. 同音替代法(比如o2o)2 2.2. 符号法(比如英文i18n ...

  2. Atitit  java jsp 新的tag技术

    Atitit  java jsp 新的tag技术 1.1.  Tag Files  vs 原生写 SimpleTag 比较麻烦的 JSP 1.x 允许 Web 开发人员创建 Java 组件(称为标记处 ...

  3. js 数组

    js中的数组类似与java中的容器 类型可以不同.长度可变 一.数组的声明 var arr1=new Array();//数组的声明一     var arr2=[1,2,3,true,new Dat ...

  4. Jquery判断页面图片是否加载失败,加载失败则显示默认图片

    例子: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. ...

  5. linux安全检查

    1 ssh后门 检察语句: grep -E "user,pas|user:pas" /usr/bin/* /usr/local/sbin/* /usr/local/bin/* /b ...

  6. JSP网站开发基础总结《一》

    经过JAVASE的学习相信大家对JAVA已经不再陌生,那么JAVA都可以干什么呢?做算法.应用程序.网站开发都可以,从今天开始为大家奉上JAVAEE之JSP动态网站开发基础总结. 既然是动态网站开发, ...

  7. Jetty集群配置Session存储到MySQL、MongoDB

    在Web开发中,Session表示HTTP服务器与客户端(例如浏览器)的“会话”,每个客户端会有其对应的Session保存在服务器端,通常用来保存和客户端关联的一些信息,例如是否登录.购物车等. Se ...

  8. HTML5的学习--performance获取加载时间的工具

    前段时间因为项目需要获取页面加载的时间,就去看了下HTML5中的performane. 可以用其获得页面详细的加载时间. 关于performance的详细内容可以查看 http://www.cnblo ...

  9. 【web前端面试题整理05】做几道前端面试题休息休息吧

    前言 连续学了两天javascript的东西了,我们都累了,于是今天还是上一套面试题吧,大家一起休息休息,也为下个星期可能会有的面试准备下. 题目一览 CSS1.  overflow-x  属于 CS ...

  10. UML简介

    Unified Modeling Language (UML)又称统一建模语言或标准建模语言,是始于1997年一个OMG标准,它是一个支持模型化和软件系统开发的图形化语言,为软件开发的所有阶段提供模型 ...