Java

  • import java.util.ArrayList;
    import java.util.List;
    import java.util.regex.Pattern;
    
    /**
    
     Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.
    
     In C++, there are two types of comments, line comments, and block comments.
    
     */
    
    public class Remove_Comments {
    
        public static void main(String[] args) {
            Remove_Comments out = new Remove_Comments();
            Solution s = out.new Solution();
    
    //        String[] input = new String[]{"int main()","{ ","  ","int a, b, c;","a = b + c;","}"};
    //
    //        System.out.println(s.removeComments(input));
    //
    //        System.out.println(s.removeComments_ac(input));
    
    
            String[] input2 = new String[]{"/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"};
    
            System.out.println(s.removeComments(input2));
            System.out.println(s.removeComments_ac(input2));
        }
    
        class Solution {
            public List<String> removeComments(String[] source) {
    
                List<String> result = new ArrayList<>();
    
                if (source == null || source.length == 0) {
                    return result;
                }
    
                boolean unclosed = false;
                Pattern line = Pattern.compile("\\/\\/");
                Pattern blockStart = Pattern.compile("\\/\\*");
                Pattern blockEnd = Pattern.compile("\\*\\/");
    
                for (String each: source) {
                    if (unclosed) { // failed by "/*Test program */", find "/*" and it's always unclosed
                        continue;
                    } else if (line.matcher(each).find()) {
                        continue;
                    } else if (blockStart.matcher(each).find()) {
                        unclosed = true;
                    } else if (blockEnd.matcher(each).find()) {
                        unclosed = false;
                    } else {
                        result.add(each);
                    }
                }
    
                return result;
            }
    
            public List<String> removeComments_ac(String[] source) {
                List<String> result = new ArrayList();
    
                if (source == null || source.length == 0) {
                    return result;
                }
    
                boolean unclosed = false;
                StringBuilder newline = new StringBuilder();
    
                for (String line: source) {
                    int i = 0;
                    char[] chars = line.toCharArray();
                    if (!unclosed) newline = new StringBuilder();
    
                    // scan through this line
                    while (i < line.length()) {
                        if (!unclosed && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '*') {
                            unclosed = true;
                            i++;
                        } else if (unclosed && i+1 < line.length() && chars[i] == '*' && chars[i+1] == '/') {
                            unclosed = false;
                            i++;
                        } else if (!unclosed && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '/') {
                            break;
                        } else if (!unclosed) {
                            newline.append(chars[i]);
                        }
    
                        i++;
                    }
    
                    if (!unclosed && newline.length() > 0) {
                        result.add(new String(newline));
                    }
                }
    
                return result;
            }
    
        }
    
    }
    
  • // OJ: https://leetcode.com/problems/remove-comments/
    // Time: O(N)
    // Space: O(1) excluding the space taken by the answer
    class Solution {
        bool match(string &s, int start, string target) {
            return start + 2 <= s.size() && s[start] == target[0] && s[start + 1] == target[1];
        }
    public:
        vector<string> removeComments(vector<string>& A) {
            vector<string> ans;
            bool block = false;
            for (int i = 0, N = A.size(); i < N; ++i) {
                int j = 0;
                if (!block) ans.emplace_back();
                while (j < A[i].size()) {
                    if (block) {
                        if (match(A[i], j, "*/")) {
                            block = false;
                            j += 2;
                        } else ++j;
                    } else if (match(A[i], j, "/*")) {
                        block = true;
                        j += 2;
                    } else if (match(A[i], j, "//")) {
                        break;
                    } else {
                        ans.back() += A[i][j++];
                    }
                } 
                if (ans.back().empty()) ans.pop_back();
            }
            return ans;
        }
    };
    
  • class Solution(object):
        def removeComments(self, source):
            """
            :type source: List[str]
            :rtype: List[str]
            """
            res = []
            multi = False
            line = ''
            for s in source:
                i = 0
                while i < len(s):
                    if not multi:
                        if s[i] == '/' and i < len(s) - 1 and s[i + 1] == '/':
                            break
                        elif s[i] == '/' and i < len(s) - 1 and s[i + 1] == '*':
                            multi = True
                            i += 1
                        else:
                            line += s[i]
                    else:
                        if s[i] == '*' and i < len(s) - 1 and s[i + 1] == '/':
                            multi = False
                            i += 1
                    i += 1
                if not multi and line:
                    res.append(line)
                    line = '' # 注意line重新设置成空字符串的位置
            return res
    
    

All Problems

All Solutions