diff --git a/Public/Valid Parentheses b/Public/Valid Parentheses new file mode 100644 index 0000000..0eefb22 --- /dev/null +++ b/Public/Valid Parentheses @@ -0,0 +1,30 @@ +// link- https://leetcode.com/problems/valid-parentheses/ +// Question: +// Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. + +// An input string is valid if: + +// 1. Open brackets must be closed by the same type of brackets. +// 2. Open brackets must be closed in the correct order. + + + +class Solution { + public boolean isValid(String s) { + LinkedList stack = new LinkedList<>(); + for(int i = 0; i < s.length(); i++) { + char ch = s.charAt(i); + if(ch == '(' || ch == '[' || ch == '{') { + stack.addFirst(ch); + } else { + if(ch == ')' && stack.size() > 0 && stack.getFirst() == '(') stack.removeFirst(); + else if(ch == ']' && stack.size() > 0 && stack.getFirst() == '[') stack.removeFirst(); + else if(ch == '}' && stack.size() > 0 && stack.getFirst() == '{') stack.removeFirst(); + else return false; + } + } + + if(stack.size() > 0) return false; + return true; + } +}