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.
Solution:
Tips:
Stack
Java Code:
public class Solution {
public boolean isValid(String s) {
Stack<Character> sc = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(' || c == '{' || c == '[') {
sc.push(c);
} else {
if (sc.empty()) {
return false;
}
char lc = sc.pop();
if (c == ')' && lc != '('
|| c == ']' && lc != '['
|| c == '}' && lc != '{') {
return false;
}
}
}
if (!sc.empty()) {
return false;
}
return true;
}
}