Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AnjaliManhas/f869f194e61f51ef6585bb2d864838fe to your computer and use it in GitHub Desktop.
Save AnjaliManhas/f869f194e61f51ef6585bb2d864838fe to your computer and use it in GitHub Desktop.
Valid Parentheses- LeetCode: 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.
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(c == '(' || c == '{' || c == '['){
stack.push(c);
}
else
{
if(stack.isEmpty()){
return false;
}
else{
if(c == ')' && stack.peek() == '('){
stack.pop();
}
else if(c == '}' && stack.peek() == '{'){
stack.pop();
}
else if(c == ']' && stack.peek() == '['){
stack.pop();
}
else{
return false;
}
}
}
}
return stack.isEmpty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment