- Valid Parentheses
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example
Consideration:
- use stack to store characters, as stack is FILO.
- If the character is ],}, ), find whether the last element in stack corresponds to its paired symbol.
3. !!! We should check if the stack is empty before get the last element in stack!
4. At the end, we should check if the stack is empty.
Ignored case
Solution
Time complexity: O(n), as we should iterate through all characters in string s.
Space complexity: O(n), as in the worst case, we should store all characters in the stack. e.g. s = “((((((((((((((((((((((((”.
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(char c: s.toCharArray()) {
if(c == '(' || c=='{' || c=='[')
stack.push(c);
else {
//check if the stack is empty first.
if(stack.size()==0)
return false;
char last = stack.pop();
if((c==')' && last!='(') ||(c=='}' && last!='{') ||(c==']' && last!='['))
return false;
}
}
if(stack.size()>0)
return false;
return true;
}
}