LeetCode题解(0722):删除代码中的注释内容(Python)
发布日期:2021-06-29 19:58:05
浏览次数:3
分类:技术文章
本文共 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月09日 09时40分52秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
QT数据类型转换篇
2019-04-30
QT读写文件篇
2019-04-30
QT UDP应用篇
2019-04-30
Laravel 安装笔记 Star.hou
2019-04-30
Laravel配置开发、测试、预上线、正式环境--Star.hou
2019-04-30
Laravel配置系统默认Log路径--Star.hou
2019-04-30
Laravel文件系统,自定义日志文件、管理文件--Star.hou
2019-04-30
Thinkphp3.2 修改session存储驱动
2019-04-30
Wamp PHP5.5.12安装Redis扩展--Star.Hou
2019-04-30
Spring Boot的基础知识
2019-04-30
java的多态
2019-04-30
Mysql,Oracle,Nosql非关系型数据库
2019-04-30
模拟数据库的操作
2019-04-30
Juquery进行表格的检索功能和Semantic-UI进行相关的样式 的修饰
2019-04-30
SpringBoot+Thymleaf+通用Mapper实现员工管理系统
2019-04-30
Buffer类型化
2019-04-30
Buffer 只读
2019-04-30
MappedByteBuffer
2019-04-30