Nested comment stripper: hints, no solution

Medium · Stack

A build tool for a small scripting language must strip comments before parsing. A comment starts at the two characters slash-star and ends at the matching star-slash. Unlike many languages, comments here can nest: every slash-star inside a comment opens another level, and the comment only ends when every level has been closed.

Read the source from left to right, two characters at a time: a marker is always two characters and is never reused, so slash-star-slash is an opening marker followed by a lone slash. A star-slash that appears outside any comment is ordinary text. A comment that is never closed runs to the end of the source.

Return the source with all comment text, markers included, removed. Everything else, including newlines, is kept as is.

Examples

Input
source = "int a; /* note */ int b;"
Output
"int a; int b;"
Note
Only the comment text goes; both spaces around it are kept.
Input
source = "x /* a /* b */ c */ y"
Output
"x y"
Note
The inner close only ends the inner comment, so the whole span is removed and only x and y remain.

Constraints

  • 0 <= source.length <= 12000
  • Source characters are printable ASCII and newlines

Hint 1: a nudge

While you are inside a comment, what does seeing another opening marker change about when you may stop skipping?

Unlock the full hints and timed practice with a pass

The second and third hints and the timed, runner-checked practice are part of a pass.

See pricing

Sign in

Check my resume first