Remove Comments

Solution For Remove Comments

Problem Statement:

Given a C++ program, remove all comments from it.

You need to parse the code and remove all the commented-out code.

A C++ comment begins with //, and extends to the end of the line. For example:

std::cout << "Hello, world!"; // A greeting

A C++ block comment begins with / and ends with /.

Block comments may extend over multiple lines.

For example:

/* This is a
multiline comment */
std::cout << "Hello, world!";

Solution:

The problem can be solved by iterating through each line of the input program and removing any occurring comments. There are two types of comments: line comments and block comments.

Line comments are easy to remove. If we find two consecutive backslashes “//”, then we can consider all characters starting from this position to the end of the line as a comment and ignore this line.

The code snippet for line comment removal would look like this:

while (pos + 1 < len && code[pos] == '/' && code[pos + 1] == '/') {
    while (pos < len && code[pos] != '\n') pos++;
}

Block comments can be a bit more challenging to remove because they can span multiple lines. We need to find the start and end positions of a block comment, and then remove all the characters between the start and end positions.

The code snippet for block comment removal would look like this:

while (pos + 1 < len && code[pos] == '/' && code[pos + 1] == '*') {
    pos += 2;
    while (pos + 1 < len && !(code[pos] == '*' && code[pos + 1] == '/')) {
        pos++;
    }
    pos += 2;
}

To implement the solution, we need to initialize a flag variable in_block_comment to false, which indicates whether we are currently inside a block comment or not.

We iterate through each character of the input program. If the current character is ‘/’ and the next character is ‘/’, we ignore all the characters till we find a new line. If the current character is ‘/’ and the next character is ‘‘, we mark the in_block_comment flag to true. If the flag is already true, we just keep ignoring all the characters till we reach ‘/’. Once we reach ‘*/’, we mark the flag to be false, and continue processing the remaining program.

Code:

Following is the implementation of the remove comments function:

string removeComments(string code) {
string ans;
bool in_block_comment = false;
int n = code.size();
for (int i = 0; i < n; ) {
if (in_block_comment) {
if (code[i] == '*' && i + 1 < n && code[i + 1] == '/') {
in_block_comment = false;
i += 2;
} else {
i++;
}
} else {
if (code[i] == '/' && i + 1 < n && code[i + 1] == '/') {
i += 2;
while (i < n && code[i] != '\n') i++;
} else if (code[i] == '/' && i + 1 < n && code[i + 1] == '*') {
in_block_comment = true;
i += 2;
} else {
ans.push_back(code[i++]);
}
}
}
return ans;
}

Time Complexity: O(n), where n is the length of the input program.

Space Complexity: O(n), where n is the length of the input program.

Step by Step Implementation For Remove Comments

/**
 * Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents 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 represents that it and rest of the characters to the right of it in the same line should be ignored.

The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */ should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning.

The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored.

If a certain 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. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (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. Please see the examples below for details.

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

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;", "}"]

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;
}

Output: ["int main()","{ ","  ","int a, b, c;","a = b + c;","}"]

Explanation: 
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.

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"].

Note:

The length of source is in the range [1, 100].
The length of source[i] is in the range [0, 80].
Every open block comment is eventually closed.
There are no single-quote, double-quote, or control characters in the source code.
 */

class Solution {
    public List removeComments(String[] source) {
        boolean inBlock = false;
        StringBuilder newline = new StringBuilder();
        List ans = new ArrayList();
        for (String line: source) {
            int i = 0;
            char[] chars = line.toCharArray();
            if (!inBlock) newline = new StringBuilder();
            while (i < line.length()) {
                if (!inBlock && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '*') {
                    inBlock = true;
                    i++;
                } else if (inBlock && i+1 < line.length() && chars[i] == '*' && chars[i+1] == '/') {
                    inBlock = false;
                    i++;
                } else if (!inBlock && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '/') {
                    break;
                } else if (!inBlock) {
                    newline.append(chars[i]);
                }
                i++;
            }
            if (!inBlock && newline.length() > 0) {
                ans.add(new String(newline));
            }
        }
        return ans;
    }
}
def removeComments(self, source):
        res = []
        i = 0
        while i < len(source):
            if source[i:i+2] == '/*' and (i == 0 or source[i-1] != '"'):
                j = i+2
                while j < len(source):
                    if source[j:j+2] == '*/':
                        break
                    j += 1
                i = j+2
            elif source[i:i+2] == '//' and (i == 0 or source[i-1] != '"'):
                j = i+2
                while j < len(source):
                    if source[j] == '\n':
                        break
                    j += 1
                i = j
            else:
                res.append(source[i])
                i += 1
        return "".join(res)
/**
 * @param {string} source
 * @return {string}
 */
var removeComments = function(source) {
    let inBlock = false;
    let res = '';
    for (let i = 0; i < source.length; i++) {
        if (inBlock) {
            if (source[i] === '*' && source[i+1] === '/') {
                inBlock = false;
                i++;
            }
        } else {
            if (source[i] === '/' && source[i+1] === '*') {
                inBlock = true;
                i++;
            } else {
                res += source[i];
            }
        }
    }
    return res;
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* removeComments(TreeNode* root) {
        if (!root) return NULL;
        string s = tree2str(root);
        int n = s.size();
        string res;
        bool block = false;
        for (int i = 0; i < n; ++i) {
            if (block) {
                if (s[i] == '*' && s[i+1] == '/') {
                    block = false;
                    ++i;
                }
                continue;
            }
            if (s[i] == '/' && s[i+1] == '*') {
                block = true;
                ++i;
                continue;
            }
            if (s[i] == '/' && s[i+1] == '/') break;
            res += s[i];
        }
        return str2tree(res);
    }
    string tree2str(TreeNode* t) {
        if (!t) return "";
        string left = tree2str(t->left);
        string right = tree2str(t->right);
        if (left == "" && right == "") return to_string(t->val);
        if (right == "") return to_string(t->val) + "(" + left + ")";
        return to_string(t->val) + "(" + left + ")" + "(" + right + ")";
    }
    TreeNode* str2tree(string s) {
        if (s == "") return NULL;
        int n = s.size(), i = 0;
        while (i < n && s[i] != '(') ++i;
        TreeNode* root = new TreeNode(stoi(s.substr(0, i)));
        int start = ++i, left = 1;
        while (i < n) {
            if (s[i] == '(') ++left;
            else if (s[i] == ')') --left;
            if (left == 0 && start == i) break;
            ++i;
        }
        root->left = str2tree(s.substr(start, i-start));
        start = ++i; left = 1;
        while (i < n) {
            if (s[i] == '(') ++left;
            else if (s[i] == ')') --left;
            if (left == 0) break;
            ++i;
        }
        root->right = str2tree(s.substr(start, i-start));
        return root;
    }
};
public IList RemoveComments(string[] source) { bool inBlock = false; var newLine = new StringBuilder(); IList ans = new List(); foreach (string line in source) { int i = 0; char[] chars = line.ToCharArray(); if (!inBlock) newLine = new StringBuilder(); while (i < line.Length) { if (chars[i] == '/' && i + 1 < line.Length && chars[i + 1] == '*') { inBlock = true; i++; } else if (inBlock && chars[i] == '*' && i + 1 < line.Length && chars[i + 1] == '/') { inBlock = false; i++; } else if (!inBlock && chars[i] == '/' && i + 1 < line.Length && chars[i + 1] == '/') { break; } else if (!inBlock) { newLine.Append(chars[i]); } i++; } if (!inBlock && newLine.Length > 0) { ans.Add(newLine.ToString()); } } return ans; }


Top 100 Leetcode Practice Problems In Java

Get 30% Off Instantly!
[gravityforms id="5" description="false" titla="false" ajax="true"]