LeetCode题解(0722):删除代码中的注释内容(Python)
发布日期:2021-06-29 19:58:05
浏览次数:2
分类:技术文章
本文共 3194 字,大约阅读时间需要 10 分钟。
题目:(中等)
标签:字符串
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( N ) O(N) O(N) | O ( 1 ) O(1) O(1) | 40ms (72.56%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Solution: def removeComments(self, source: List[str]) -> List[str]: removing = False # 是否在被多行屏蔽的情况下 ans = [] idx = 0 in_line = False while idx < len(source): line = source[idx] # 读取当前行信息 if removing: if "*/" in line: removing = False source[idx] = line[line.index("*/") + 2:] else: idx += 1 else: N = len(line) idx_1 = line.index("//") if "//" in line else N idx_2 = line.index("/*") if "/*" in line else N if idx_1 < idx_2 and "//" in line: if in_line and ans: content = ans.pop() + line[:line.index("//")] in_line = False else: content = line[:line.index("//")] if content: ans.append(content) idx += 1 elif idx_1 > idx_2: if in_line and ans: ans.append(ans.pop() + line[:line.index("/*")]) else: ans.append(line[:line.index("/*")]) source[idx] = line[line.index("/*") + 2:] removing = True in_line = True else: if in_line and ans: content = ans.pop() + line in_line = False else: content = line if content: ans.append(content) idx += 1 return ans
解法二(整理解法一代码):
class Solution: def removeComments(self, source: List[str]) -> List[str]: is_block = False # 是否在被多行屏蔽的情况下 in_line = False # 当前是否换行 ans = [] idx = 0 while idx < len(source): line = source[idx] # 读取当前行信息 if is_block: # 处理当前正在多行屏蔽的情况下 if "*/" in line: is_block = False source[idx] = line[line.index("*/") + 2:] else: idx += 1 else: content = ans.pop() if in_line and ans else "" # 当前行结果 idx_1 = line.index("//") if "//" in line else float("inf") idx_2 = line.index("/*") if "/*" in line else float("inf") if idx_1 < idx_2: in_line = False content += line[:line.index("//")] if content: ans.append(content) idx += 1 elif idx_1 > idx_2: is_block, in_line = True, True ans.append(content + line[:line.index("/*")]) source[idx] = line[line.index("/*") + 2:] else: in_line = False content += line if content: ans.append(content) idx += 1 return ans
转载地址:https://dataartist.blog.csdn.net/article/details/108061493 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2024年04月05日 14时22分04秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
奇异值分解简要笔记
2021-07-03
6.824(2020年) Lab1 MapReduce
2021-07-03
6.824 Amazon Aurora云数据库
2021-07-03
6.824 2020 Lecture 13: Spanner
2021-07-03
数据库恢复 (ARIES)
2019-04-30
比特币Bitcoin论文笔记
2019-04-30
Apache Flink: 在同一个引擎做流式和批处理
2019-04-30
CMU15-445 PROJECT 4 - LOGGING & RECOVERY
2019-04-30
Amazon Dynamo论文以及与Cassandra对比
2019-04-30
常见26种NLP任务的练手项目(收藏)
2019-04-30
【GNN】task5-超大图上的节点表征学习
2019-04-30
智能教学系统 Cognitive Tutors: Lessons Learned
2019-04-30
使用免费GPU深度学习平台colab玩转Kaggle比赛
2019-04-30
研究知识追踪/学生模型的一些学校和人物
2019-04-30
简谈RSS——巧用Feed43制作自定义RSS源
2019-04-30
powershell 脚本压缩工具
2019-04-30
Windows下Pentaho Report Designer之运行配置
2019-04-30
【python数据可视化】穷逼买二手房历险记
2019-04-30