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.循环遍历数组,扫描每个字符;
2.判断当前字符,如果是左括号符号时,将该字符压入栈中;
3.判断当前字符如果是右括号符号时,弹出栈顶符号;
4.然后栈顶元素与当前字符进行匹配,如果不匹配,返回false,如果匹配继续下一字符的扫描。
5.扫描结束后,判断当前栈中是否还有元素,如果为空,返回true,表明匹配成功;如果不为空,则返回false,表明匹配失败。
public boolean isValid(String s) {
if(s.length() % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<Character>();
char[] code = s.toCharArray();
for (int i = 0; i < code.length; i++) {
if(code[i]=='(' || code[i] == '{' || code[i] == '[') {
stack.push(code[i]);
}
if(code[i]==')' || code[i] == '}' || code[i] == ']') {
if(!stack.isEmpty()) {
Character c = stack.pop();
if((c == null)||(!match(c,code[i]))) {
return false;
}
}
}
}
if(stack.isEmpty()) {
return true;
}else {
return false;
}
}
public boolean match(char left,char right)
{
boolean ret = false;
switch(left)
{
case '[': ret = (right == ']'); break;
case '(': ret = (right == ')'); break;
case '{': ret = (right == '}'); break;
default:
ret = false;
break;
}
return ret;
}