Leetcode Problem 722 - Remove Comments
You are given a list of strings source
where each string represents a single line of source code. This list of source code is to be viewed as an entire concatenated string, with each line being concatenated end-to-end with a newline delimiter.
You need to remove the comments from the source code. The comment types are:
//
): These comments start with //
and extend to the end of a line./* */
): These comments start with /*
and extend to the next occurrence of */
. These can span multiple lines.Return the source code after removing the comments. The result should be a list of strings, where each string represents a single line of the resulting code.
Given that these are typical problems, let’s proceed with the structure assuming sane inputs.
in_block_comment
(boolean) to check if we are inside a block comment.result
to store the processed lines of code.new_line
to collect characters for the current line being processed.new_line
list.Here is how you might implement this in Java:
import java.util.ArrayList;
import java.util.List;
public class RemoveComments {
public List<String> removeComments(String[] source) {
List<String> result = new ArrayList<>();
boolean inBlockComment = false;
StringBuilder newLine = new StringBuilder();
for (String line : source) {
int i = 0;
if (!inBlockComment) {
newLine = new StringBuilder();
}
while (i < line.length()) {
if (!inBlockComment && i + 1 < line.length() && line.charAt(i) == '/' && line.charAt(i + 1) == '/') {
break; // Line comment detected, ignore rest of the line
} else if (!inBlockComment && i + 1 < line.length() && line.charAt(i) == '/' && line.charAt(i + 1) == '*') {
inBlockComment = true; // Block comment starts
i++;
} else if (inBlockComment && i + 1 < line.length() && line.charAt(i) == '*' && line.charAt(i + 1) == '/') {
inBlockComment = false; // Block comment ends
i++;
} else if (!inBlockComment) {
newLine.append(line.charAt(i)); // Add non-comment characters
}
i++;
}
if (!inBlockComment && newLine.length() > 0) {
result.add(newLine.toString());
}
}
return result;
}
public static void main(String[] args) {
RemoveComments rc = new RemoveComments();
String[] source = {
"/*Test program */",
"int main()",
"{ ",
" // variable declaration ",
"int a, b, c;",
"/* This is a test",
" multiline ",
" comment for ",
" testing */",
"a = b + c;",
"}"
};
List<String> output = rc.removeComments(source);
for (String line : output) {
System.out.println(line);
}
}
}
This approach ensures that the entire source code is processed efficiently while properly handling nested and multiline 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?