# LeetCode: 722. 删除注释¶

## 1、题目描述¶

C++ 中有两种注释风格，行内注释和块注释。

输入:
source = ["/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"]

/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}

int main()
{

int a, b, c;
a = b + c;
}



输入:
source = ["a/*comment", "line", "more_comment*/b"]



• source的长度范围为[1, 100].
• source[i]的长度范围为[0, 80].
• 每个块注释都会被闭合。
• 给定的源码中不会有单引号、双引号或其他控制字符。

## 2、解题思路¶

• 对于单行注释和多行注释分别处理
• 设置一个标志位，确认当前是否找到了多行注释的结束标记
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans = []
length = len(source)

line = "//"
many_left = "/*"
many_right = "*/"

pre = 0
pos = 0
temp = ""
while pos < length:
cur = source[pos]
if pre:
index = cur.find(many_right)
if index != -1:
source[pos] = temp + cur[index + 2:]
pos -= 1
pre = 0
else:
source[pos] = ""
else:
line_index = cur.find(line)
many_index = cur.find(many_left)
if line_index != -1 and many_index == -1 or (line_index != -1 and line_index < many_index):
source[pos] = cur[:line_index]
elif line_index == -1 and many_index != -1 or (many_index != -1 and many_index < line_index):
temp_pos = cur.find(many_right, many_index + 2)
if temp_pos != -1:
source[pos] = cur[:many_index] + cur[temp_pos + 2:]
pos -= 1
else:
pre = 1
temp = cur[:many_index]
source[pos] = ""
pos += 1

return [x for x in source if x]