Valid Parentheses
来源:互联网 发布:下载软件推荐 编辑:程序博客网 时间:2024/05/29 03:30
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.建栈:
Stack<Character> sk = new Stack<Character>();
2.测试栈是否为空:
sk.empty();
3.移除栈顶,并返回值:
sk.pop();
4.查看栈顶,不移除:
sk.peek();
5.压入栈顶:
sk.push();
package leetcode;
import java.util.Stack;
public class ValidParentheses {
public staticboolean isValid(String s) {
boolean ans =true;
Stack<Character> sk = new Stack<Character>();
if (s == "" || s.length() == 0) returnans;
if (s.length() % 2 != 0)return false;
char[] chars =s.toCharArray();
for (int i = 0; i<chars.length;i++){
if (chars[i] =='{' || chars[i] =='[' || chars[i] =='('){
sk.push(chars[i]);
}
if (chars[i] =='}' ){
if (sk.empty()){
ans =false;
break;
}
if (sk.pop() =='{'){
ans =true;
}else {
ans =false;
break;
}
}
if (chars[i] ==']' ){
if (sk.empty()){
ans =false;
break;
}
if (sk.pop() =='['){
ans =true;
}else {
ans =false;
break;
}
}
if (chars[i] ==')' ){
if (sk.empty()){
ans =false;
break;
}
if (sk.pop() =='('){
ans =true;
}else {
ans =false;
break;
}
}
}
if (!sk.empty())ans = false;
return ans;
}
public staticvoid main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isValid("[["));
}
}
- 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
- HTTP协议
- HDU ACM 4501 小明系列故事——买年货->多维背包(多为01背包)
- Win7、VS2010、OpenCV2.3.1 出现:“无法启动此程序,因为计算机中丢失tbb_debug.dll.尝试重新安装该(转)
- struts2 的 result type详解
- HTML
- Valid Parentheses
- Redis常用命令
- JavaWeb学习02-03
- linux入门基础——linux网络配置
- 在mfc中使用cef
- [leetcode] Implement strStr()
- Objective C 中的nil,Nil,NULL和NSNull理解
- akoj-1076-Encoding
- 东方之星