-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
43 lines (40 loc) · 1.88 KB
/
ValidParentheses.java
File metadata and controls
43 lines (40 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.*;
public class ValidParentheses {
public boolean isValid(String s){
//Creates a stack to keep track of the characters in the string
Stack<Character> stack = new Stack<>();
if (s.length() == 0){
return false;
}
//Converts the String s to a character array
//For loop iterates through every character
for(char c: s.toCharArray()){
//If there is an opening (, {, or [, push the corresponding closing
//bracket onto the stack
if(c =='('){
stack.push(')');
}
else if (c == '{'){
stack.push('}');
}
else if (c == '['){
stack.push(']');
}
//if the char is not an opening parentheses, pop off the top of the stack,
//if the char being popped off (top of stack) does not match the char being read, return false
//if the stack is empty, return false
/* Once a closing parentheses is read in the string, the top of the stack should be popped off to see
* if it matches the char being read. If the string contains valid parentheses, the char being popped off
* and the char being read will match because we pushed the corresponding closing parentheses on the stack
* and opening brackets must be closed in the correct order */
else if (stack.isEmpty() || stack.pop() !=c){
return false;
}
}
/* If the stack is empty, it means that all closing brackets that were pushed on to the stack
were popped off because their corresponding characters were read in the string. This means that the string
contained valid parentheses and would therefore return True.
*/
return stack.isEmpty();
}
}