Removing Stars From a String
Delete every star in a string together with the closest letter on its left, in one pass.
Given a string s*
Example 1
Output: "coe"
Explanation: the first star removes 's', the second removes the first 'c', and the third removes 'd'.
Example 2
Output: ""
Explanation: five stars remove all five letters.
The Idea
A star behaves like the backspace key. When you type cssccodecoe
Each press of backspace removes the letter typed most recently among those still on the screen. A star does the same, because the closest letter on its left that is still there is the newest one kept so far. Look at the picture below, which reads cs**cod*e
The top row is the character read, and below it are the kept letters after it, with the newest one on top. The letters cssccoddecoe
So a star never needs to search. The letter it removes is always the one on top of the pile. A pile where you only add and remove at the top is called a stack, and the last item added is the first one taken out.
Solution Approach
Turning the pile into code comes down to three points: why a stack beats editing the string star by star, which Java type to use as the stack, and how to read the answer out of it in the right order.
Searching for each star's letter
What if we just edit the string, star by star? For each star, walk left to the closest letter, then delete both from the string. Walking left and deleting from the middle of a string can each take as many steps as the string is long. With n characters and up to n/2 stars, that adds up to about n² steps.
The stack avoids both costs. Reading left to right, each letter is added on top, and each star removes the top. Neither step depends on how long the string is.
A StringBuilder as the stack
Which Java type should hold the kept letters? A StringBuilderappenddeleteCharAt(length() - 1)
Reading the answer in the right order
How do the kept letters become the answer? In the StringBuildertoString()
A Deque<Character>pop()
Java Solution
The method removeStars
- First, create an empty
namedStringBuilder . It is the stack of kept letters, with its end as the top.kept - Loop over the characters of
from left to right, one characters at a time.c - When
is a star, remove the last character ofc withkept . The problem promises a letter is always there to remove.deleteCharAt(kept.length() - 1) - Otherwise
is a letter, so add it to the end ofc withkept .append(c) - After the loop, return
.kept.toString()
The main""
public class RemovingStarsFromString {
public static String removeStars(String s) {
StringBuilder kept = new StringBuilder(); // used as a stack of letters
for (char c : s.toCharArray()) {
if (c == '*') {
kept.deleteCharAt(kept.length() - 1); // drop the most recent kept letter
} else {
kept.append(c); // keep the letter, on top
}
}
return kept.toString();
}
public static void main(String[] args) {
System.out.println("\"" + removeStars("cs**cod*e") + "\"");
System.out.println("\"" + removeStars("erase*****") + "\"");
System.out.println("\"" + removeStars("stack") + "\"");
System.out.println("\"" + removeStars("ab*c**d") + "\"");
System.out.println("\"" + removeStars("x*y*z*") + "\"");
}
}
Running it prints:
"coe"
""
"stack"
"d"
""
"coe""""stack"
Look at the fourth line, "d"ab*c**dbaccadx*y*z*
Here is the DequepushpopStringBuilder
import java.util.ArrayDeque;
import java.util.Deque;
public class DequeOrderCheck {
public static void main(String[] args) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : "cs**cod*e".toCharArray()) {
if (c == '*') {
stack.pop();
} else {
stack.push(c);
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
System.out.println("popped in order: \"" + sb + "\"");
System.out.println("reversed: \"" + sb.reverse() + "\"");
}
}
Running it prints:
popped in order: "eoc"
reversed: "coe"
The first line, "eoc"ereverse()"coe"
The original implementation,
Complexity
The work is one pass over the string, with one small step per character.
- Time: O(n), because each of the n characters is read once and causes either one
or one delete at the end ofappend , and neither moves other characters.kept - Space: O(n), because
can hold every character when there are no stars, andkept makes one more copy of the input.toCharArray()
A related problem removes any k equal letters that end up side by side, for a number k it is given: see