2
public List<String> removeComments(String[] source) {4
false; // We keep track of whether or not we are within a block comment with the blockActive6
// It is initally set to false since we haven't read anything until now.8
List<String> result = new ArrayList<String>();9
StringBuilder builder = new StringBuilder();11
// Read every line from the source input.13
for (String line : source) {14
// Each time we move on to reading a new line, we check if it is a part of a block comment.15
// If it is already part of a block comment, it means we should skip the implicit newline16
// characters as mentioned in the problem description.17
// For example if Line 1 was "int a /*Block comment Started" and Line 2 was "Block comment18
// ends here */ b;", and Line 3 was "int c;"19
// we want our output to be "int ab", "int c" instead of "int a", "b;", "int c;"21
builder = new StringBuilder();23
for (int i = 0; i < line.length(); i++) { // Read every character of line24
char c = line.charAt(i);25
if (!blockActive) { // If we aren't currently in a block27
if (c == '/') { // We check if we encounter the start of a regular comment28
// If so, then we need to check if the next character makes it a regular comment, a29
// block comment, or neither of those two.31
if (i < line.length() - 132
&& line.charAt(i + 1) == '/') { // Checking if it's a regular comment33
break; // If it's a regular comment, we can simply skip everything else34
// until the end of the line, so we break from the loop and move on to the next line.35
} else if (i < line.length() - 1 && line.charAt(i + 1) == '*') { // Or a block comment36
i++; // Since we verified it's a block comment, we simply increment i so that we don't37
// re-read the '*' again,38
// and mark that we are now part of a block comment.40
} else { // If the second character is neither a / or *, it indicates that a first41
// character must be a valid operator42
// (probably a mathematical operator such as multiplication or division, and not part44
// so simply append it to the builder)47
} else { // Append all other characters directly to the builder.51
// We skip all other characters in a block comment, and check for the closing block53
// Once we find it, we mark the blockActive variable as false to indicate that it isn't54
// part of the block anymore.56
if (i < line.length() - 1 && line.charAt(i + 1) == '/') {63
// We append to the result when we aren't part of a block any more, and the builder contains 164
// or more characters.65
if (!blockActive && builder.length() != 0) {66
result.add(builder.toString());