20. Valid Parentheses
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.
public class Solution {
public boolean isValid(String s) {
if (s == null || s.length() % 2 == 1) {
return false;
}
Map<Character, Character> parenMap = new HashMap<Character, Character>();
parenMap.put(')', '(');
parenMap.put(']', '[');
parenMap.put('}', '{');
char [] parenChars = s.toCharArray();
Stack<Character> currentParen = new Stack<Character>();
for (char parenChar : parenChars) {
Character targetValue = parenMap.get(parenChar);
if (targetValue == null) {
currentParen.push(parenChar);
} else {
if (currentParen.isEmpty()) {
return false;
}
if (! currentParen.pop().equals(targetValue)){
return false;
}
}
}
if (currentParen.isEmpty()) {
return true;
}
return false;
}
}
public class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put(']','[');
map.put('}','{');
Stack<Character> stack = new Stack<>();
for(char ch : s.toCharArray()){
if(ch == '(' || ch == '[' || ch == '{'){
stack.push(ch);
}else{
char pair = map.get(ch);
if(stack.isEmpty() || stack.peek() != pair) return false;
else stack.pop();
}
}
return stack.isEmpty();
}
}