Python solution with "join" trick


  • 0
    Y

    Python solution with "join" trick

    class Solution:
        def removeComments(self, source):
            """
            :type source: List[str]
            :rtype: List[str]
            """
            # Easier to handle if everything is just one stream of character
            all_string = "\n".join(source)
            i = 0
            result_string = ""
            while i < len(all_string):
                two = all_string[i:i+2]
                if two == "//":
                    # If you find '//', move 2 chracters ahead and
                    # keep moving until you find newline ('\n') or EOF
                    i += 2
                    while i < len(all_string) and all_string[i] != "\n":
                        i += 1
                elif two == "/*":
                    # If you find '/*', move 2 characters ahead and start to search for '*/'
                    # After you find one, move 2 characters ahead again.
                    i += 2
                    while all_string[i:i+2] != "*/":
                        i += 1
                    i += 2
                else:
                    # Append character to result_string if it is not a part of comment
                    result_string += all_string[i]
                    i += 1
            # If a certain line of code is empty after removing comments, 
            # you must not output that line: each string in the answer list will be non-empty.
            return [line for line in result_string.split("\n") if line != ""]
    

Log in to reply
 

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