Skip to content
Advertisement

Efficient solution to codingBat riddle starOut in Java

The problem I am talking about is this

Problem statment:

Return a version of the given string, where for every star () in the string the star and the chars immediately to its left and right are gone. So “abcd” yields “ad” and “ab**cd” also yields “ad”.

starOut(“ab*cd”) → “ad”

starOut(“ab**cd”) → “ad”

starOut(“sm*eilly”) → “silly”

The solution I got was a little messy I have used about 6 if statements and a handling for one particular case, looking for cleaner solutions with lesser ifs.

Please do not use more than 1 loop and collections or regex.

Below is my solution:

JavaScript

Advertisement

Answer

Pseudocode:

Step through all the characters in the string. If you land on an asterisk, don’t record it. Peek left, and if you see an asterisk, don’t record it. Peek right if you see an asterisk, don’t record it. If none of the above things happen, record it.

Java code:

JavaScript

Note: I see a lot of answers pop up that are concatenating String objects in the loop instead of using a StringBuilder. Don’t do that. It’s very inefficient.

Advertisement