LeetCode----- 20.Valid Parentheses
来源:互联网 发布:win7下装linux双系统 编辑:程序博客网 时间:2024/06/07 16:10
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.
由于只包含字符的字符串'('
,')'
,'{'
,'}'
,'['
和']'
,确定输入字符串是有效的。
括号匹配思路:
1.循环遍历数组,扫描每个字符;
2.判断当前字符,如果是左括号符号时,将该字符压入栈中;
3.判断当前字符如果是右括号符号时,弹出栈顶符号;
4.然后栈顶元素与当前字符进行匹配,如果不匹配,返回false,如果匹配继续下一字符的扫描。
5.扫描结束后,判断当前栈中是否还有元素,如果为空,返回true,表明匹配成功;如果不为空,则返回false,表明匹配失败。
public boolean isValid(String s) { if(s.length() % 2 != 0) { return false; } Stack<Character> stack = new Stack<Character>(); char[] code = s.toCharArray(); for (int i = 0; i < code.length; i++) { if(code[i]=='(' || code[i] == '{' || code[i] == '[') { stack.push(code[i]); } if(code[i]==')' || code[i] == '}' || code[i] == ']') { if(!stack.isEmpty()) { Character c = stack.pop(); if((c == null)||(!match(c,code[i]))) { return false; } } }} if(stack.isEmpty()) { return true; }else {return false;} }public boolean match(char left,char right){boolean ret = false;switch(left){case '[': ret = (right == ']'); break;case '(': ret = (right == ')'); break;case '{': ret = (right == '}'); break;default:ret = false;break;}return ret;}
阅读全文
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode-20.Valid Parentheses
- LeetCode *** 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- leetcode-20. Valid Parentheses
- Mybatis 调用数据库的存储过程
- Android清除缓存功能实现
- sm3算法
- 《Windows核心编程》读书笔记八 用户模式下的内核同步
- 荣之联正式发布大数据平台,这和大多数产品不太一样
- LeetCode----- 20.Valid Parentheses
- 什么是 Zend ? 什么是 PHP ?
- C语言入门第十篇,switch语句练习题
- 多牛传媒推出智能化新媒体平台,谷歌发布两项云端自然语言处理功能 | 大数据24小时
- 专访阿里金融云徐敏:为普惠金融地提供技术原力
- 金融科技&大数据产品推荐:兴业研究地方政府信用评级产品
- Linux Mint 17.3 Rosa下JDK编译
- 第5章 遮羞的艺术——Windows游戏绘图技巧
- post提交数据时显示异常