Repository navigation
Expand file tree
/
Copy pathStack.java
More file actions
107 lines (94 loc) · 2.56 KB
/
Copy pathStack.java
File metadata and controls
107 lines (94 loc) · 2.56 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
LeetCode: 20. Valid Parentheses
Difficulty: Easy
Pattern: Stack and Bracket Sequences
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
if(ch == '(' || ch == '[' || ch == '{'){
stack.push(ch);
} else {
if(ch == ')'){
if(stack.isEmpty() || stack.pop() != '(' ){
return false;
}
}
if(ch == ']'){
if(stack.isEmpty() || stack.pop() != '[' ){
return false;
}
}
if(ch == '}'){
if(stack.isEmpty() || stack.pop() != '{' ){
return false;
}
}
}
}
return stack.isEmpty();
}
}
*/
/*
LeetCode: 32. Longest Valid Parentheses
Difficulty: Hard
Pattern: Stack and Bracket Sequences
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<>();
stack.push(-1);
int maxLength = 0;
for(int i = 0; i < s.length(); i++){
if(s.charAt(i) == '('){
stack.push(i);
}else{
stack.pop();
if(stack.isEmpty()){
stack.push(i);
}else{
maxLength = Math.max(maxLength, i - stack.peek());
}
}
}
return maxLength;
}
}
*/
/*
LeetCode: 735. Asteroid Collision
Difficulty: Medium
Pattern: Stack and Simulation
class Solution {
public int[] asteroidCollision(int[] asteroids) {
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < asteroids.length ; i++){
boolean destroyed = false;
while(!stack.isEmpty() && stack.peek() > 0
&& asteroids[i] < 0){
if(stack.peek() < -asteroids[i]){
stack.pop();
}
else if(stack.peek() == -asteroids[i]){
stack.pop();
destroyed = true;
break;
}
else {
destroyed = true;
break;
}
}
if(!destroyed){
stack.push(asteroids[i]);
}
}
int[] ans = new int[stack.size()];
for(int i = ans.length - 1 ; i>=0 ; i--){
ans[i] = stack.pop();
}
return ans;
}
}
*/