[
string
parser
]
Leetcode 0722 Remove Comments
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.
- If we met
/*
and we are not in block than we say, that we are in block now, and increasei
by2
(by1
here, and by1
in the end) - If we met
*/
and we are in block, then we say that we are not in block anymore and again increasei
by2
. - If we are not in block and we met
//
, it means, we need to remove the following part of the string, so we break - If we are not in block (and all other options are already checked), then we add element to buffer.
- 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 putbuffer = ""
.
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