Problem Description
Given a list of strings representing lines of C++ source code, remove all the comments. There are two types of comments: line comments (starting with //) and block comments (starting with /* and ending with */). After processing, any line that becomes empty must not be included in the final output.
Key Insights
- Use a flag to track when you are inside a block comment.
- For each line, process character by character.
- Ignore characters inside block comments.
- When encountering a line comment marker (//) while not in a block comment, ignore the rest of that line.
- If starting a block comment, mark the flag and skip characters until the block ends.
- Append the processed line to the result only if it is non-empty and not in a continuing block comment.
Space and Time Complexity
Time Complexity: O(n * m) where n is the number of lines and m is the average length of each line. Space Complexity: O(n * m) in worst case due to storing the output, plus a negligible amount for flags and temporary variables.
Solution
The approach involves iterating through each line and each character in the line while maintaining a flag (in_block) to indicate if the current context is inside a block comment. When not inside a block comment, characters are appended to a temporary list that builds the actual code line. Once a line comment (//) is encountered, skip the rest of the line. When a block comment beginning (/) is found, switch the flag and ignore characters until the block comment is terminated by (/). After processing a line, if not in a block comment and the temporary list has content, join the characters and add the line to the resulting list.