您的位置:首页 > 其它

20 Valid Parentheses

2016-03-15 16:47 429 查看
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<Integer> stk = new Stack<Integer>();
for (int i = 0; i < s.length(); ++i) {
int pos = "(){}[]".indexOf(s.substring(i, i + 1));
if (pos % 2 == 1) {
if (stk.isEmpty() || stk.pop() != pos - 1)
return false;
} else {
stk.push(pos);
}
}
return stk.isEmpty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: