forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveStars.java
More file actions
36 lines (31 loc) · 921 Bytes
/
RemoveStars.java
File metadata and controls
36 lines (31 loc) · 921 Bytes
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
package com.thealgorithms.strings;
/**
* Removes characters affected by '*' in a string.
* Each '*' deletes the closest non-star character to its left.
*
* Example:
* Input: leet**cod*e
* Output: lecoe
*/
public final class RemoveStars {
private RemoveStars() {
// Private constructor to prevent instantiation(object creation)
}
public static String removeStars(String s) {
StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) {
if (c == '*') {
if (result.length() > 0) {
result.deleteCharAt(result.length() - 1);
}
} else {
result.append(c);
}
}
return result.toString();
}
public static void main(String[] args) {
String example = "leet**cod*e";
System.out.println(removeStars(example));
}
}