1.题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
2.思想
使用栈,匹配则返回true
3. 代码
public boolean isValid(String s) {
if (s.equals("")) {
return true;
}
Stack<Character> stack = new Stack<Character>();
//栈中先任意存放一个元素,防止栈空
stack.push('a');
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '(':
stack.push(s.charAt(i));
break;
case '{':
stack.push(s.charAt(i));
break;
case '[':
stack.push(s.charAt(i));
break;
case ')':
if (stack.peek() == '(')
stack.pop();
else
stack.push(s.charAt(i));
break;
case '}':
if (stack.peek() == '{')
stack.pop();
else
stack.push(s.charAt(i));
break;
default:
if (stack.peek() == '[')
stack.pop();
else
stack.push(s.charAt(i));
}
}
return stack.peek() == 'a';
}