您的位置:首页 > 编程语言 > Java开发

[Leetcode] Valid Parentheses (Java)

2013-12-26 15:08 387 查看
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.

括号匹配,没考虑//,/* */," "等

import java.util.Stack;

public class ValidParentheses {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c=='('||c=='[')
stack.add(c);
else if(c==')'){
if(!stack.isEmpty()&&stack.peek()=='(')
stack.pop();
else
return false;
}else if(c==']'){
if(!stack.isEmpty()&&stack.peek()=='[')
stack.pop();
else
return false;
}
}
if(stack.isEmpty())
return true;
return false;
}
public static void main(String[] args) {
String s = "(([()]))[]";
System.out.println(new ValidParentheses().isValid(s));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: