-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
49 lines (40 loc) · 1.16 KB
/
Copy pathSolution.java
File metadata and controls
49 lines (40 loc) · 1.16 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
44
45
46
47
48
49
package org.example.problems.valid_parentheses;
import org.example.problems.SolutionInterface;
import java.util.Stack;
public class Solution implements SolutionInterface {
@Override
public String getName() {
return "Valid Parentheses";
}
@Override
public String getUrl() {
return "https://leetcode.com/problems/valid-parentheses/";
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c: s.toCharArray()) {
if (isOpen(c)) {
stack.push(c);
} else {
if (stack.empty()) {
return false;
}
char open = stack.pop();
if (!isMatch(open, c)) {
return false;
}
}
}
return stack.empty();
}
private boolean isOpen(char c) {
return c == '['
|| c == '('
|| c == '{';
}
private boolean isMatch(char open, char closed) {
return (open == '[' && closed == ']')
|| (open == '(' && closed == ')')
|| (open == '{' && closed == '}');
}
}