Skip to content

Instantly share code, notes, and snippets.

@AnjaliManhas
Created May 6, 2020 14:07
Show Gist options
  • Save AnjaliManhas/31b5042eef30078d093b7c5aea8c5c8c to your computer and use it in GitHub Desktop.
Save AnjaliManhas/31b5042eef30078d093b7c5aea8c5c8c to your computer and use it in GitHub Desktop.
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.
class Solution {
public boolean isValid(String s) {
HashMap<Character,Character> maps=new HashMap<Character,Character>();
maps.put(')','(');
maps.put(']','[');
maps.put('}','{');
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(maps.containsKey(c)){
if(stack.empty()||stack.pop()!=maps.get(c))return false;
}
else
stack.push(c);
}
return stack.empty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment