Skip to content

Commit 65745af

Browse files
refactor 402
1 parent 26c7e48 commit 65745af

File tree

2 files changed

+29
-31
lines changed

2 files changed

+29
-31
lines changed

src/main/java/com/fishercoder/solutions/_402.java

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,27 +25,28 @@
2525
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
2626
*/
2727
public class _402 {
28-
29-
/**credit: https://discuss.leetcode.com/topic/59412/a-greedy-method-using-stack-o-n-time-and-o-n-space*/
30-
public String removeKdigits(String num, int k) {
31-
int digits = num.length() - k;
32-
char[] stack = new char[num.length()];
33-
int top = 0;
34-
35-
for (int i = 0; i < num.length(); i++) {
36-
char c = num.charAt(i);
37-
while (top > 0 && stack[top - 1] > c && k > 0) {
38-
top--;
39-
k--;
28+
public static class Solution1 {
29+
30+
/** credit: https://discuss.leetcode.com/topic/59412/a-greedy-method-using-stack-o-n-time-and-o-n-space */
31+
public String removeKdigits(String num, int k) {
32+
int digits = num.length() - k;
33+
char[] stack = new char[num.length()];
34+
int top = 0;
35+
36+
for (int i = 0; i < num.length(); i++) {
37+
char c = num.charAt(i);
38+
while (top > 0 && stack[top - 1] > c && k > 0) {
39+
top--;
40+
k--;
41+
}
42+
stack[top++] = c;
4043
}
41-
stack[top++] = c;
42-
}
4344

44-
int index = 0;
45-
while (index < digits && stack[index] == '0') {
46-
index++;
45+
int index = 0;
46+
while (index < digits && stack[index] == '0') {
47+
index++;
48+
}
49+
return index == digits ? "0" : new String(stack, index, digits - index);
4750
}
48-
return index == digits ? "0" : new String(stack, index, digits - index);
4951
}
50-
5152
}

src/test/java/com/fishercoder/_402Test.java

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,16 @@
66

77
import static org.junit.Assert.assertEquals;
88

9-
/**
10-
* Created by stevesun on 6/3/17.
11-
*/
129
public class _402Test {
13-
private static _402 test;
10+
private static _402.Solution1 solution1;
1411

15-
@BeforeClass
16-
public static void setup() {
17-
test = new _402();
18-
}
12+
@BeforeClass
13+
public static void setup() {
14+
solution1 = new _402.Solution1();
15+
}
1916

20-
@Test
21-
public void test1() {
22-
assertEquals("1219", test.removeKdigits("1432219", 3));
23-
}
17+
@Test
18+
public void test1() {
19+
assertEquals("1219", solution1.removeKdigits("1432219", 3));
20+
}
2421
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy