Leetcode 722: Remove Comments

grid47
grid47
Exploring patterns and algorithms
Aug 26, 2024 7 min read

A source code where comments are removed, with the comments fading out and the code glowing softly.
Solution to LeetCode 722: Remove Comments Problem

You are given a C++ program represented as an array of strings, where each string corresponds to a line of code. Your task is to remove all comments from the code. The two types of comments in C++ are line comments (//) and block comments (/* … */). After removing comments, return the modified code as an array of strings, excluding any empty lines.
Problem
Approach
Steps
Complexity
Input: An array of strings representing lines of a C++ program.
Example: ["/*This is a test program*/", "int main()", "{", " // This is a variable declaration", "int a, b, c;"]
Constraints:
• 1 <= source.length <= 100
• 0 <= source[i].length <= 80
• No single or double quotes in the input
• Every open block comment will eventually be closed
Output: Return the modified program as an array of strings where all comments are removed, and empty lines are excluded.
Example: ["int main()", "{", " int a, b, c;", " a = b + c;", "}"]
Constraints:
• Each output string will be non-empty.
Goal: To remove comments from the given C++ program code and return the cleaned code.
Steps:
• Iterate through each line of the source code.
• Identify and skip characters inside block comments (/*...*/).
• Identify line comments (//) and ignore the remainder of the line.
• Ensure that lines which become empty after removing comments are not included in the result.
Goal: The input will always contain valid and properly closed comments.
Steps:
• Each string in the input contains printable ASCII characters.
• There will be no single-quote or double-quote characters.
• Every open block comment will eventually be closed.
Assumptions:
• The input is always valid with properly closed comments.
• There are no macros or defines that affect the comments.
Input: Example 1
Explanation: In this example, the block comment removes multiple lines and part of a line, while the line comment removes everything after the '//' in the line.

Input: Example 2
Explanation: Here, the block comment starts and ends in the middle of the string, removing implicit newlines between 'a' and 'b'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus