Skip to content

Commit

Permalink
Create 20 Valid Parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
tom-cruise-coder committed Feb 21, 2021
1 parent 7bd1195 commit 17a0b4e
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions 20 Valid Parentheses
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
20. Valid Parentheses
Given a string s 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.


Example 1:

Input: s = "()"
Output: true
Example 2:

Input: s = "()[]{}"
Output: true

public boolean isValid(String s) {

Stack<Character> stack = new Stack(); //O(n)
for(char c : s.toCharArray()){ //O(n)
if(c=='(' || c=='[' || c=='{'){
stack.add(c);
}else{
if(stack.isEmpty())return false;
if(c==']' && stack.peek()!='[')return false;
if(c==')' && stack.peek()!='(')return false;
if(c=='}' && stack.peek()!='{')return false;
stack.pop();
}
}

return stack.isEmpty();
}

0 comments on commit 17a0b4e

Please sign in to comment.