Problem statement

https://leetcode.com/problems/remove-comments/

Solution

Let us iterate over our data line by line and consider several cases. Also keep variable in_block which is indicator if we are in block or not.

  1. If we met /* and we are not in block than we say, that we are in block now, and increase i by 2 (by 1 here, and by 1 in the end)
  2. If we met */ and we are in block, then we say that we are not in block anymore and again increase i by 2.
  3. If we are not in block and we met //, it means, we need to remove the following part of the string, so we break
  4. If we are not in block (and all other options are already checked), then we add element to buffer.
  5. In the end of each line we check if buffer is not empty and we are not in the block, then add this line to res and put buffer = "".

Complexity

Time complexity is O(n) to proceed all data once, space complexity potentially O(n) as well.

Code

class Solution(object):
    def removeComments(self, source):
        res, buffer, in_block = [], "", False
        for line in source:
            i = 0
            while i < len(line):
                if line[i:i+2] == "/*" and not in_block:
                    in_block = True
                    i += 1
                elif line[i:i+2] == "*/" and in_block:
                    in_block = False
                    i += 1
                elif not in_block and line[i:i+2] == "//":
                    break
                elif not in_block:
                    buffer += line[i]
                i += 1
                    
            if buffer and not in_block:
                res.append(buffer)
                buffer = ""
        return res