LeetCode Problem 722: Remove Comments
You are given a list of source code source
where source[i]
is the i-th
line of the source code. This is formatted in a list where each string is a single line of the code.
Comments can appear in three forms:
/*
and end with */
. They can span multiple lines.//
and end at the end of the same line.The task is to return the source code after removing the comments and keeping the format of the original code lines which are not part of any comment.
*/
).//
) or block comment (/*
).N
is the number of lines and M
is the maximum length of a line.Here’s the implementation in Python:
def removeComments(source):
in_block_comment = False
result = []
new_line = []
for line in source:
i = 0
while i < len(line):
if in_block_comment:
if line[i:i + 2] == '*/':
in_block_comment = False
i += 2
else:
i += 1
else:
if line[i:i + 2] == '/*':
in_block_comment = True
i += 2
elif line[i:i + 2] == '//':
break
else:
new_line.append(line[i])
i += 1
if not in_block_comment and new_line:
result.append("".join(new_line))
new_line = []
return result
# Example usage:
source_code = [
"/*Test program */",
"int main()",
"{ ",
" // variable declaration ",
"int a, b, c;",
"/* This is a test",
" multiline ",
" comment for ",
" testing */",
"a = b + c;",
"}"
]
print(removeComments(source_code))
This implementation addresses the problem by carefully checking for each type of comment indicator and managing the state transitions between inside and outside of comments.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?