"""
Use stack datasture;
Pay attention to different testcases:
"[" | false
"{({{{{" | false
"" | true
"[]" | true
"{[(])}" | false
"{{[()]}}" | true
"}}))" | false
"""
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True;
pairs = {
'(' : ')',
'{' : '}',
'[' : ']'
}
stack = [];
for i in range(len(s)):
if s[i] in pairs:
stack.append(s[i]);
else:
if not stack or pairs[stack[-1]] != s[i]:
return False;
elif pairs[stack[-1]] == s[i]:
stack.pop();
if not stack:
return True;
else:
return False;
public class Solution {
public boolean isValid(String s) {
if (s == null || s.length() < 1) return true;
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
Deque<Character> stack = new ArrayDeque<>();
char[] str = s.toCharArray();
int len = s.length();
for (int i = 0; i < len; i++) {
if(map.containsKey(str[i])) {
stack.push(str[i]);
} else if (stack.isEmpty() || str[i] != map.get(stack.peek())) { // "]"
return false;
} else {
stack.pop();
}
}
return stack.isEmpty();
}
}
public class Solution {
public boolean isValid(String s) {
if (s.isEmpty()) return true;
char[] chars = s.toCharArray();
char[] stack = new char[chars.length + 1];
stack[0] = '-';
int p = 1;
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
switch(c) {
case '(':
stack[p++] = ')';
break;
case '[':
stack[p++] = ']';
break;
case '{':
stack[p++] = '}';
break;
default:
if (stack[--p] != c) return false;
}
}
return p == 1;
}
}