-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
44 lines (41 loc) · 1.69 KB
/
solution.py
File metadata and controls
44 lines (41 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Code generated by https://github.com/goodstudyqaq/leetcode-local-tester
"""
try:
from utils.python3.help import *
except ImportError:
pass # In leetcode environment, we don't need to import the help file.
class Solution:
def removeComments(self, source: List[str]) -> List[str]:
ans = []
n = len(source)
now = 0
while now < n:
# find // and /*
idx1 = source[now].find("//")
idx2 = source[now].find("/*")
if idx1 == -1 and idx2 == -1:
# both not found, append the whole line
ans.append(source[now])
now += 1
continue
idx1 = idx1 if idx1 != -1 else 1e9
idx2 = idx2 if idx2 != -1 else 1e9
# find the min
if idx1 < idx2:
# // is before /*. So we can just append the line before //
source[now] = source[now][:source[now].index("//")]
ans.append(source[now])
now += 1
elif idx2 < idx1:
# /* is before //. we need to find the */ and merge the line before /* and the line after */
tmp = source[now][:source[now].index("/*")]
source[now] = source[now][source[now].index("/*") + 2:] # Pay attention: we need to remove the first part.
while now < n:
if "*/" in source[now]:
source[now] = tmp + source[now][source[now].index("*/") + 2:]
break
else:
now += 1
# After find the */, we just merge and don't append the line.
return [x for x in ans if x != ""]