Sponsored
Sponsored
This approach involves iterating through each line of the source code while managing a flag to detect if we are currently in a block comment. As we parse each line, we handle three different states: whether we are inside a block comment, encountering a line comment, or processing regular code.
Time Complexity: O(n*m), where n is the number of lines and m is the average length of each line. Space Complexity: O(n*m), for the resulting list storage.
1#include <vector>
2#include <string>
3using namespace std;
4
5vector<string> removeComments(vector<string>& source) {
6 vector<string> result;
7 string newline;
8 bool inBlock = false;
9 for (string& line : source) {
10 int i = 0;
11 if (!inBlock) newline = "";
12 while (i < line.size()) {
13 if (!inBlock && i + 1 < line.size() && line[i] == '/' && line[i+1] == '*') {
14 inBlock = true;
15 i++;
16 } else if (inBlock && i + 1 < line.size() && line[i] == '*' && line[i+1] == '/') {
17 inBlock = false;
18 i++;
19 } else if (!inBlock && i + 1 < line.size() && line[i] == '/' && line[i+1] == '/') {
20 break;
21 } else if (!inBlock) {
22 newline.push_back(line[i]);
23 }
24 i++;
25 }
26 if (!inBlock && !newline.empty()) {
27 result.push_back(newline);
28 }
29 }
30 return result;
31}
This solution iterates over each character in every line. It toggles the inBlock flag upon encountering block comment delimiters. Line comment markers cause the remainder of the line to be ignored. Any non-comment part of the line is stored in newline, which is added to result when complete.
In this approach, two pointers are used. A pointer iterates through the string to seek comment delimiters ('//', '/*', '*/') while another manages the indices of the non-commented part of each line. It is effective in keeping track of multi-line parsing for block comments.
Time Complexity: O(n*m), where n is the number of lines and m is the average length of each line. Space Complexity: O(n*m), needed for result list and string manipulations.
1import java.util.*;
2
3
This Java solution uses two-pointers to iterate through the input lines. A StringBuilder is used to construct non-commented sections of the code as we iterate each line. By utilizing subnet comparisons, the approach efficiently detects comment starter and end patterns and processes the valid source code accordingly.