forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemovingStars.java
More file actions
45 lines (43 loc) · 1.24 KB
/
RemovingStars.java
File metadata and controls
45 lines (43 loc) · 1.24 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
package main.java.com.thealgorithms.strings;
import java.util.*;
/**
* A utility class to remove stars ('*') from a given string.
* Each '*' deletes the character immediately before it.
*
* <p>Example:
* <pre>
* Input: "leet**cod*e"
* Output: "lecoe"
* </pre>
*
* <p>This implementation uses a stack-like approach for efficient character removal.
* @author Ganesh Mane
*/
public final class RemovingStars{
private RemovingStars(){
//prevent instantiation
}
/**
* Removes stars from the given string, simulating backspace behavior.
*
* @param text the input string possibly containing '*'
* @return the final string after removing stars and their preceding characters
*/
public static void main(String[] args) {
String s = "leet**cod*e";
System.out.println(removeStarsFromString(s));
}
public static String removeStarsFromString(String s){
StringBuilder sb = new StringBuilder();
for(char ch : s.toCharArray()){
if(ch == '*'){
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
}else{
sb.append(ch);
}
}
return sb.toString();
}
}