这段代码中发生了什么:
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
in_block = False
ans = []
for line in source:
print("current line:", line)
i = 0
if not in_block:
newline = []
while i < len(line):
if line[i:i+2] == '/*' and not in_block:
in_block = True
i += 1
elif line[i:i+2] == '*/' and in_block:
in_block = False
i += 1
elif not in_block and line[i:i+2] == '//':
break
elif not in_block:
print("line:", line, "line i:", line[i], "newline", newline)
newline.append(line[i])
print("newline after:", newline)
i += 1
if newline and not in_block:
ans.append("".join(newline))
print("ans:", ans)
return ans
newline
是在一行的每次迭代中创建的source
(如果未打开块注释),那么newline
当当前行位于“ b”时,代码如何以“ a”获得?
input: ["a/*comment", "line", "more_comment*/b"]
print:
current line: a/*comment
line: a/*comment line i: a newline []
newline after: ['a'] <= this makes sense, after removing everything after /*
current line: line <= this makes sense, we ignore this because the block comment is still open
current line: more_comment*/b <= at this last line, block comment is still open
line: more_comment*/b line i: b newline ['a'] <== this isn't supposed to happen
newline after: ['a', 'b'] <= how?
ans: ['ab']
在当前行=“ more_comment * / b”处,它是输入索引2处的项目source
,newline
不应存在于该行,因为它是在for循环内创建的。
我可以理解这种解决方案,因为在buffer
循环之外创建了,并且每次将追加到后都会清除它output
。但是,上面的代码使我完全困惑。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句