The problem involves removing comments from a source code represented as a list of strings. In the code, comments can be either:
//
which extend to the end of the current line./*
and ending with */
which can span multiple lines.The task is to return the source code after removing all the comments.
Here’s a possible C++ implementation:
#include <vector>
#include <string>
std::vector<std::string> removeComments(std::vector<std::string>& source) {
std::vector<std::string> result;
bool inBlockComment = false;
std::string newLine;
for (const std::string &line : source) {
int i = 0;
if (!inBlockComment) newLine.clear(); // start fresh if not in block comment
while (i < line.length()) {
if (!inBlockComment && i + 1 < line.length() && line[i] == '/' && line[i + 1] == '*') {
inBlockComment = true;
i += 2; // skip the "/*"
} else if (inBlockComment && i + 1 < line.length() && line[i] == '*' && line[i + 1] == '/') {
inBlockComment = false;
i += 2; // skip the "*/"
} else if (!inBlockComment && i + 1 < line.length() && line[i] == '/' && line[i + 1] == '/') {
break; // ignore the rest of the line
} else if (!inBlockComment) {
newLine.push_back(line[i]);
i++;
} else {
i++;
}
}
if (!inBlockComment && !newLine.empty()) {
result.push_back(newLine);
}
}
return result;
}
The time complexity of this solution is O(n * m), where ( n ) is the number of lines and ( m ) is the maximum length of a line. This is because in the worst case, we iterate through each character of all lines.
By following this structured approach, we ensure that the solution is both efficient and easy to understand.
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?