Remove Comments
expert · 1080 · lc medium +32 · verified · 40% accepted · 756 likes · top 19%
Description
You are given an array of strings source representing the lines of a C++ source file (split on newline). Strip all C++ comments from it and return the remaining non-empty lines.
C++ has two comment types:
- "//" starts a line comment — everything from "//" to the end of that line is discarded.
- "/*" starts a block comment — everything through the matching "*/" (read left to right, line by line) is discarded; block comments can span multiple lines and delete implicit newlines.
The first active comment syntax wins (e.g., "//" inside a block comment is ignored). Every "/*" that opens a block comment outside any other comment is guaranteed to eventually close. Output lines that become empty after stripping are omitted.
Example 1:
Example 2:
Code