Recursive parsing O(N) python

  • 0
    class Solution(object):
        def removeComments(self, source):
            :type source: List[str]
            :rtype: List[str]
            def process_line(line, in_block_comment):
                if not line: 
                    # if line is empty, do nothing
                    return line,in_block_comment
                output = ''
                if not in_block_comment:
                    # find if there is block comment, or line comment substring in given line
                    block_comment_st = line.find('/*') 
                    line_comment_st  = line.find('//')
                    block_comment_st = block_comment_st if block_comment_st >= 0 else float('inf')
                    line_comment_st  = line_comment_st if line_comment_st >= 0 else float('inf')
                    # find out who happens early
                    comment_st = min(line_comment_st, block_comment_st)
                    if comment_st == float('inf'):
                        # no comment characters
                        return line,False
                    elif comment_st == line_comment_st:
                        # line comment starting
                        return line[:line_comment_st], False
                    elif comment_st == block_comment_st:
                        # block comment starting
                        output = line[:block_comment_st]
                        next_part, next_in_block_comment = process_line(line[block_comment_st+2:], True)
                        return output + next_part, next_in_block_comment
                    # we're in block comment, and so find if any ends
                    block_comment_en = line.find('*/')
                    if block_comment_en >= 0:
                        return process_line(line[block_comment_en+2:], False)
                        return '',True
            result   = []
            in_blck  = False
            for line in source:
                if not in_blck:
                    output, in_blck = process_line(line,in_blck)
                    if output:
                        result += output,
                    output, in_blck = process_line(line,in_blck)
                    if output:
                        result[-1] += output
            return result

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.