-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathanswer.java
More file actions
19 lines (19 loc) · 825 Bytes
/
answer.java
File metadata and controls
19 lines (19 loc) · 825 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
// Iterate through string
for(int i = 0; i < s.length(); i++){
// Put opening into stack
if(s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
stack.push(s.charAt(i));
// If it is a closing character, pop from stack if matches
else if((s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(') ||
(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{') ||
(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '['))
stack.pop();
// Else it is not valid
else return false;
}
return stack.empty();
}
}