您的位置:首页 > 其它

LeetCode----20. Valid Parentheses

2016-09-20 14:59 507 查看
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.

Subscribe to see which companies asked this question
"()[]"  "("    "(()[])"   "([()])"

Runtime Error Message:Line
8: java.lang.StringIndexOutOfBoundsException: String index out of range: 2

Last executed input:"(("
"[({(())}[()])]"

public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (Character c : s.toCharArray()) {
if ("({[".contains(String.valueOf(c))) {
stack.push(c);
} else {
if (!stack.isEmpty() && is_valid(stack.peek(), c)) {
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}

private boolean is_valid(char c1, char c2) {
return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}')
|| (c1 == '[' && c2 == ']');
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: