问题:
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.
解决:
①一个个检查给定的字符,如果是左括号都入栈;如果是右括号,检查栈如果为空,证明不能匹配,如果栈不空,弹出top,与当前扫描的括号检查是否匹配。全部字符都检查完了以后,判断栈是否为空,空则正确都匹配,不空则证明有没匹配的。
注意:
检查字符是用==,检查String是用.isEqual(),因为String是引用类型,值相等但是地址可能不等。
public class Solution {//13ms
public boolean isValid(String s) {
if(s.length() <= 1) return false;
Stack<Character> tmp = new Stack<>();//用于存储左括号
for (int i = 0;i < s.length() ;i ++ ) {
if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
tmp.push(s.charAt(i));
}else{
if(tmp.size() == 0) return false;
char top = tmp.pop();
if(s.charAt(i) == ')')
if(top != '(') return false;
if(s.charAt(i) == ']')
if(top != '[') return false;
if(s.charAt(i) == '}')
if(top != '{') return false;
}
}
return tmp.size() == 0;
}
}
进阶版:在遍历到左括号时,将右括号入栈,这样,只需要比较栈中的右括号与便利到的右括号是否相等即可。
public class Solution {//10ms
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(')
stack.push(')');
else if (c == '[')
stack.push(']');
else if (c == '{')
stack.push('}');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
}
② 使用数组编写栈结构,效率更高一些。
public class Solution {//7 ms
public boolean isValid(String s) {
if (s.isEmpty()) return true;
char[] schar = s.toCharArray();
char[] stack = new char[schar.length + 1];
stack[0] = '-';//为防止数组下标越界
int p = 1;
for (int i = 0; i < schar.length; i ++) {
char c = schar[i];
switch(c) {
case '(':
stack[p ++] = ')';
break;
case '[':
stack[p ++] = ']';
break;
case '{':
stack[p ++] = '}';
break;
default://若case语句都不匹配,则执行该语句
if (stack[-- p] != c) return false;
}
}
return p == 1;
}
}
使用if-else
public class Solution {
public boolean isValid(String s) {
char[] stack = new char[s.length()];
int p = 0;
if(s.length() % 2 != 0) return false;
for (int i = 0;i < s.length() ;i ++ ) {
if('(' == s.charAt(i)) stack[p ++] = ')';
else if('[' == s.charAt(i)) stack[p ++] = ']';
else if('{' == s.charAt(i)) stack[p ++] = '}';
else{
if(p > 0 && s.charAt(i) == stack[-- p]) continue;
else{
return false;
}
}
}
return p == 0;
}
}
来源:oschina
链接:https://my.oschina.net/u/2968041/blog/1305287