#722

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:

Input: source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
Output: ["int main()","{ "," ","int a, b, c;","a = b + c;","}"]
Explanation: The line by line code is visualized as below:
/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}

Example 2:

Input: source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].

Code

1
2
3