Created
May 6, 2020 14:04
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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