-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack2LC.java
More file actions
71 lines (62 loc) · 2.1 KB
/
stack2LC.java
File metadata and controls
71 lines (62 loc) · 2.1 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
import java.util.Stack;
/*
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (isOperator(token)) {
int b = stack.pop();
int a = stack.pop();
int result = applyOperation(a, b, token);
stack.push(result);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
private boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
private int applyOperation(int a, int b, String op) {
switch(op) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b; // Integer division
default: throw new IllegalArgumentException("Invalid operator: " + op);
}
}
public static void main(String[] args) {
Solution sol = new Solution();
String[] tokens = {"2","1","+","3","*"}; // Example
System.out.println(sol.evalRPN(tokens)); // Output: 9
}
}
*/ //1209 leetcode
class Solution {
public String removeDuplicates(String s, int k) {
// Stack stores character and its frequency
Stack<int[]> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (!stack.isEmpty() && stack.peek()[0] == ch) {
stack.peek()[1]++;
if (stack.peek()[1] == k) {
stack.pop(); // remove k duplicates
}
} else {
stack.push(new int[]{ch, 1});
}
}
// Build result
StringBuilder sb = new StringBuilder();
for (int[] pair : stack) {
char c = (char) pair[0];
int count = pair[1];
while (count-- > 0) {
sb.append(c);
}
}
return sb.toString();
}
}