Valid Parentheses
来源:互联网 发布:北大青鸟网络课程介绍 编辑:程序博客网 时间:2024/06/05 02:45
https://oj.leetcode.com/problems/valid-parentheses/
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.
题意:括号匹配,要求同种括号一一对应,不能嵌套
思路:用栈存放左括号,如果遇到右括号则pop出比较,如果对不上则表示匹配失败。最终全部比较完后如果栈中不为空,则匹配失败,否则表示匹配成功
实现:
public class Solution { public boolean isValid(String s ) { List< Character> left=new LinkedList<Character>(); char[]arr =s .toCharArray(); for(int i =0;i <s .length();i++){ if(arr [i ]=='(' ||arr [i ]=='[' ||arr [i ]=='{' )//如果是左括号,则入栈 left.add( arr[ i]); else{ if(left .size()==0)//如果栈为空,则匹配不成功 return false ; char t =left .get(left .size()-1);//取出栈顶元素 left.remove( left.size()-1); switch(arr [i ]){ case ')' : if(t !='(' ) return false ; break; case ']' : if(t !='[' ) return false ; break; case '}' : if(t !='{' ) return false ; break; } } } if(left .size()!=0)//如果栈不为空,表示左括号多了,匹配不成功 return false ; return true ; }}
0 0
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- Valid Parentheses
- android 集成支付宝
- 读书笔记: effective C++; 条款22 和 23, 尽量用传址少用传值。
- 素数环精品
- cocos2d-x 3.2 文字显示方法代码
- 机器可以怎样学习
- Valid Parentheses
- 数据结构--remove方法对LinkedList类的使用注意
- HDU 3887 Counting Offspring(dfs序的应用)
- Ubuntu下安装cgal4.5.2计算几何库
- Adobe Photoshop CS6提示”无法完成请求,因为文件格式模块不能解析该文件“
- 几个项目规划畅想etc.
- opencv2在视频帧序列中运用鼠标extract rectangle region
- 自学数据挖掘十大算法之PageRank
- LeetCode: Rotate Array