Given a C++ program, remove comments from it. The program source is an array of strings source where source[i] is the ith 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.
The string “//” denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
The string “/" denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of "/” should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string “/*/” does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
For example, if the string “//” occurs in a block comment, it is ignored.
Similarly, if the string “/*” occurs in a line or block comment, it is also ignored.
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.
There will be no control characters, single quote, or double quote characters.
For example, source = “string s = “/* Not a comment. */”;” will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so “/*” outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return the source code in the same format.
这题 我愿意称之为 字符串顶流题
这题看着不难,但坑很多。
先来弄清楚一些情况比如:
// abcdef /*
这里的/*是可以忽略的 就是一旦出现 “//“ 那//之后的内容都忽略
/* abc // 这也是一样 // 是可以忽略的,一旦有/* 后面的内容都是comment直到 */出现
a/* hahaha **/b
或者
a/ * haha
haha */ b
的结果都是 ab
也就是说注释符号前后的 内容我们是要保留的
同理
abc // eve
这里保留的是 abc
还有其他要素,要素过多
1 不要有typo, / * , * / 是左斜杠
2 这里直接去一整行判断,比如 if /* in sentence
,是不行的因为 可能一行可能同时含有 //, /* 和 * /
3 这里最棘手的就是 /* 因为受他影响, 一个普通的行也会被忽略,他是一个超越单行句子之外的影响因素,自然想到要设立一个flag来记录是不是正被/*包裹
并且在遍历每个字符串的时候 都要给这个flag做一次判断
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans = []
star = False
content = ""
for s in source:
# if in /* state, the content need be connected with content before /*
if not star:
content = ""
i = 0
while i < len(s):
# all use if elif, every judgement should have a star flag
if s[i:i+2] == "/*" and not star:
i+=1
# need add one to jump this comment signal
star = True
elif s[i:i+2] == "//" and not star:
i += 1
break
elif s[i:i+2] == "*/" and star:
star = False
i += 1
elif not star:
content += s[i]
i += 1
if content!="" and not star:
ans.append(content)
return ans