Valid parentheses
来源:互联网 发布:itunes管理iphone软件 编辑:程序博客网 时间:2024/05/04 08:55
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.
分析:
用stack解决,一个一个检查character,如果是左括号就放入stack;如果是右括号,看stack是否为空,若为空则不匹配,若不为空,判断pop出的是否匹配。全部检查完后,看stack是否为空,若空则valid,若不空证明还有没有匹配的所以不valid。
code:
publicclass Solution {
public boolean isValid(String s) {
if (s.length() == 0 || s.length() == 1) {
return false;
}
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) =='(' || s.charAt(i) == '[' || s.charAt(i) =='{') {
stack.push(s.charAt(i));
} else {
if (stack.size() == 0) {
returnfalse;
}
char top = stack.pop();
if (s.charAt(i) ==')') {
if (top !='(') {
returnfalse;
}
} else if (s.charAt(i) == '}') {
if (top !='{') {
returnfalse;
}
} else if (s.charAt(i) == ']'){
if (top !='[') {
returnfalse;
}
}
}
}
return stack.size() == 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
- SharedPreferences详解
- asd
- Android Canvas类介绍
- 你不知道的29种营销秘籍《二》
- 串联谐振拓扑分析之升降压式DC-DC变换器
- Valid parentheses
- javascript必知必会之this关键字及scope
- 找北大同学
- 黑马程序员-Java基础知识
- vector的内存分配 新理解
- Valid parentheses - leetcode
- Java程序员的JavaScript学习笔记(2——属性复制和继承)
- <<Python基础教程>>学习笔记 | 第14章 | 网络编程
- Unity调用PC摄像头