722. Remove Comments LeetCode Solution

In this guide, you will get 722. Remove Comments LeetCode Solution with the best time and space complexity. The solution to Remove Comments problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Remove Comments solution in C++
  4. Remove Comments solution in Java
  5. Remove Comments solution in Python
  6. Additional Resources
722. Remove Comments LeetCode Solution image

Problem Statement of Remove Comments

Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith 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 the 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.

For example, 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.

See also  1000. Minimum Cost to Merge Stones LeetCode Solution

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;”, “}”]
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”].

See also  1125. Smallest Sufficient Team LeetCode Solution

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.

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

722. Remove Comments LeetCode Solution in C++

class Solution {
 public:
  vector<string> removeComments(vector<string>& source) {
    vector<string> ans;
    bool commenting = false;
    string modified;

    for (const string& line : source) {
      for (int i = 0; i < line.length();) {
        if (i + 1 == line.length()) {
          if (!commenting)
            modified += line[i];
          ++i;
          break;
        }
        const string& twoChars = line.substr(i, 2);
        if (twoChars == "/*" && !commenting) {
          commenting = true;
          i += 2;
        } else if (twoChars == "*/" && commenting) {
          commenting = false;
          i += 2;
        } else if (twoChars == "//") {
          if (!commenting)
            break;
          else
            i += 2;
        } else {
          if (!commenting)
            modified += line[i];
          ++i;
        }
      }
      if (modified.length() > 0 && !commenting) {
        ans.push_back(modified);
        modified = "";
      }
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

722. Remove Comments LeetCode Solution in Java

class Solution {
  public List<String> removeComments(String[] source) {
    List<String> ans = new ArrayList<>();
    boolean commenting = false;
    StringBuilder modified = new StringBuilder();

    for (final String line : source) {
      for (int i = 0; i < line.length();) {
        if (i + 1 == line.length()) {
          if (!commenting)
            modified.append(line.charAt(i));
          ++i;
          break;
        }
        String twoChars = line.substring(i, i + 2);
        if (twoChars.equals("/*") && !commenting) {
          commenting = true;
          i += 2;
        } else if (twoChars.equals("*/") && commenting) {
          commenting = false;
          i += 2;
        } else if (twoChars.equals("//")) {
          if (!commenting)
            break;
          else
            i += 2;
        } else {
          if (!commenting)
            modified.append(line.charAt(i));
          ++i;
        }
      }
      if (modified.length() > 0 && !commenting) {
        ans.add(modified.toString());
        modified.setLength(0);
      }
    }

    return ans;
  }
}
// code provided by PROGIEZ

722. Remove Comments LeetCode Solution in Python

class Solution:
  def removeComments(self, source: list[str]) -> list[str]:
    ans = []
    commenting = False
    modified = ''

    for line in source:
      i = 0
      while i < len(line):
        if i + 1 == len(line):
          if not commenting:
            modified += line[i]
          i += 1
          break
        twoChars = line[i:i + 2]
        if twoChars == '/*' and not commenting:
          commenting = True
          i += 2
        elif twoChars == '*/' and commenting:
          commenting = False
          i += 2
        elif twoChars == '//':
          if not commenting:
            break
          else:
            i += 2
        else:
          if not commenting:
            modified += line[i]
          i += 1
      if modified and not commenting:
        ans.append(modified)
        modified = ''

    return ans
# code by PROGIEZ

Additional Resources

See also  65. Valid Number LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.