Referred to this post.
If we see ‘//’ we stop reading the current line, and add whatever characters we have seen to the result. If we see ‘/’ then we start the multiline comment mode and we keep on ignoring characters until we see ‘/’. If the current character is neither of the above two and the multiline comment mode is off, then we add that character to the current line.
class Solution {
public List<String> removeComments(String[] source) {
List<String> res = new ArrayList<>();
boolean isBlockComment = false;
StringBuilder sb = new StringBuilder();
for (String s : source) {
for (int i = 0; i < s.length(); i++) {
if (isBlockComment) {
if (s.charAt(i) == '*' && i < s.length() - 1 && s.charAt(i + 1) == '/') {
isBlockComment = false;
i++;
}
} else {
if (s.charAt(i) == '/' && i < s.length() - 1 && s.charAt(i + 1) == '/') {
break;
} else if (s.charAt(i) == '/' && i < s.length() - 1 && s.charAt(i + 1) == '*') {
isBlockComment = true;
i++;
} else {
sb.append(s.charAt(i));
}
}
}
if (!isBlockComment && sb.length() > 0) {
res.add(sb.toString());
sb = new StringBuilder();
}
}
return res;
}
}