public class Solution {
public boolean isValid(String s) {
Stack<Character> sc = new Stack<>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
switch (c) {
case '(':
case '[':
case '{':
sc.push(c);
break;
case ')':
if (sc.isEmpty() || sc.peek() != '(' )
return false;
else
sc.pop();
break;
case ']':
if (sc.isEmpty() || sc.peek() != '[' )
return false;
else
sc.pop();
break;
case '}':
if (sc.isEmpty() || sc.pop() != '{' )
return false;
break;
default:
break;
}
}
return sc.isEmpty();
}
}
---------------------------------
HINT:
1. 栈的使用
2. 思路:左边全部入栈;从第一个右边的符号开始逐个‘钓’出栈中的元素,如果钓失败,匹配失败;如果全部钓到,最后栈空。
===================
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.