LeetCode 20. Valid Parentheses(括号校验)
2016-05-19 06:50
369 查看
原题网址:https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
方法:使用栈进行配对。
另一种实现:使用数组实现栈。
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.
方法:使用栈进行配对。
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(int i=0; i<s.length(); i++) { char ch = s.charAt(i); if (ch == '(' || ch == '[' || ch == '{') stack.push(ch); else { if (stack.isEmpty()) return false; char last = stack.pop(); if ((last == '(' && ch == ')') || (last == '[' && ch == ']') || (last == '{' && ch == '}')) continue; return false; } } return stack.isEmpty(); } }
另一种实现:使用数组实现栈。
public class Solution { public boolean isValid(String s) { char[] sa = s.toCharArray(); int stack = 0; for(int i=0; i<sa.length; i++) { if (sa[i]=='(' || sa[i]=='[' || sa[i]=='{') sa[stack++] = sa[i]; else if (stack == 0) return false; else if (sa[stack-1] != '(' && sa[i]==')') return false; else if (sa[stack-1] != '[' && sa[i]==']') return false; else if (sa[stack-1] != '{' && sa[i]=='}') return false; else stack --; } return stack == 0; } }
相关文章推荐
- complex类 序列化时 IsRequired = true 问题
- 【华为OJ】【084-求最大连续bit数】
- 编程思想之多线程与多进程(4)——C++中的多线程
- 【华为OJ】【083-计算字符串的相似度】
- 还需要补充很多知识
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- (加精)AndrodStudio 极光推送 推送类手写版加精Demo 续写!!!
- leetcode 11 in c++
- 【华为OJ】【082-字符串通配符】
- LeetCode 18. 4Sum(四数之和)
- 船已开始颠簸,大家坐好
- 【华为OJ】【081-查找两个字符串a,b中的最长公共子串】
- 【Unity】13.3 Realtime GI示例
- 源码推荐(0519):PickerView,星星形状的评分进度条
- 【Unity】13.2 通过Lighting Window设置相关参数
- LeetCode 17. Letter Combinations of a Phone Number(键盘字母)
- Swagger - 前后端分离后的契约
- 【Unity】13.1 场景视图中的GI可视化
- 转载 C#中敏捷开发规范
- LeetCode 16. 3Sum Closest(最接近的和)