Mid/SeniorArrayString

Remove Comments

Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the i^th line of the source code, representing the result of splitting the original source code string by the newline character \n.

In C++, there are two types of comments: line comments and block comments.

  • The string "//" denotes a line comment, which means it and the rest of the characters to its right in the same line should be ignored.
  • The string "/*" denotes a block comment, which means all characters until the next non-overlapping occurrence of "*/" should be ignored. Occurrences are considered in reading order: line by line from left to right. The string "/*/" does not end the block comment because the ending would overlap the beginning.

The first effective comment takes precedence over others.

  • If the string "//" occurs inside a block comment, it is ignored.
  • If the string "/*" occurs inside a line comment or block comment, it is also ignored.

If a line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.

There will be no control characters, single quote, or double quote characters. Also, nothing else such as defines or macros will interfere with the comments.

It is guaranteed that every open block comment will eventually be closed, so "/*" outside of a line or block comment always starts a new comment.

Finally, implicit newline characters can be deleted by block comments.

After removing the comments from the source code, return the source code in the same format.

Example 1
Inputsource = ["/*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;","}"]
Block comments remove the first line and lines 6 through 9, while the line comment removes the variable declaration comment text, leaving only the listed non-empty code lines.
Example 2
Inputsource = ["a/*comment","line","more_comment*/b"]
Output["ab"]
The block comment spans across implicit newline characters, so deleting it joins a and b into ab.

Constraints

  • 1 <= source.length <= 100
  • 0 <= source[i].length <= 80
  • source[i] consists of printable ASCII characters.
  • Every open block comment is eventually closed.
  • There are no single-quote or double-quote in the input.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate