You can start by implementing a slow version, it can be much faster than you think. But let them say it too slowly. Then this is an optimization problem. Where does inefficiency lie?
- "if a number" is easy, you can use a regular expression or anything that stops when it finds something that is not a number.
- “if the next word is a number” is just as easy to implement effectively.
Now this is the “remove asterisk” part, which is your problem. The key point here is that you do not need to duplicate the line: you can change it in place, as you only delete items.
Try to do this visually before trying to implement it.
Keep two integers or iterators, the first one says that you are currently reading your line, and the second says where you are writing your line now. Since you are only deleting material, the read will always be ahead of the written.
If you decide to keep the current line, you just need to advance each of the integers / iterators one by one and copy accordingly. If you do not want to store it, just push the reading line! Then you only need to cut the string by the number of stars you have deleted. Complexity is just O (n), without using any extra buffer.
Also note that your algorithm will be simpler (but equivalent) if it is written as follows:
wasNumber = false Loop through string if number set wasNumber = true else set wasNumber = false if asterisk and wasNumber and next word is a number do nothing // using my algorithm, "do nothing" actually copies what you intend to keep else remove asterisk
source share