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
38 lines (38 loc) · 1.3 KB
/
RemoveStars.java
File metadata and controls
38 lines (38 loc) · 1.3 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
package com.thealgorithms.strings;
/**
* @author Swarit Srivastava (https://github.com/SwarritSrivastava)
*/
public final class RemoveStars {
private RemoveStars() {
}
/**
* Removes stars ('*') from the given string according to the following rules:
* <ul>
* <li>For each star in the string, remove the closest non-star character to its left
* along with the star itself.</li>
* <li>Return the final string after performing all removals.</li>
* <li>Given that such operation is always possible for the input</li>
* </ul>
*
* Example: {@code "leet**cod*e" -> "lecoe"}
*
* @param input The input string possibly containing '*' characters.
* @return The resulting string after removing stars as per the rules.
*/
public static String removeStars(String input) {
if (input == null || input.isEmpty()) {
return input;
}
int n = input.length();
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++) {
char currentChar = input.charAt(i);
if (currentChar != '*') {
result.append(currentChar);
} else {
result.deleteCharAt(result.length() - 1);
}
}
return result.toString();
}
}