题目如下:

Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n.

In C++, there are two types of comments, line comments, and block comments.

The string // denotes a line comment, which represents that it and rest of the characters to the right of it in the same line should be ignored.

The string /* denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of */ should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string /*/does not yet end the block comment, as the ending would be overlapping the beginning.

The first effective comment takes precedence over others: if the string // occurs in a block comment, it is ignored. Similarly, if the string /* occurs in a line or block comment, it is also ignored.

If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.

There will be no control characters, single quote, or double quote characters. For example, source = "string s = "/* Not a comment. */";" will not be a test case. (Also, nothing else such as defines or macros will interfere with the comments.)

It is guaranteed that every open block comment will eventually be closed, so /* outside of a line or block comment always starts a new comment.

Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.

After removing the comments from the source code, return the source code in the same format.

Example 1:

Input:
source = ["/*Test program */", "int main()", "{ ", "  // variable declaration ", "int a, b, c;", "/* This is a test", "   multiline  ", "   comment for ", "   testing */", "a = b + c;", "}"]The line by line code is visualized as below:
/*Test program */
int main()
{ // variable declaration
int a, b, c;
/* This is a testmultiline  comment for testing */
a = b + c;
}Output: ["int main()","{ ","  ","int a, b, c;","a = b + c;","}"]The line by line code is visualized as below:
int main()
{ int a, b, c;
a = b + c;
}Explanation:
The string /* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.

Example 2:

Input:
source = ["a/*comment", "line", "more_comment*/b"]
Output: ["ab"]
Explanation: The original source string is "a/*comment\nline\nmore_comment*/b", where we have bolded the newline characters.  After deletion, the implicit newline characters are deleted, leaving the string "ab", which when delimited by newline characters becomes ["ab"].

Note:

  • The length of source is in the range [1, 100].
  • The length of source[i] is in the range [0, 80].
  • Every open block comment is eventually closed.
  • There are no single-quote, double-quote, or control characters in the source code.

解题思路:这种题目还是很烦的,要考虑的情况比较多。我的方法相对简单粗暴一点,首先设置一个定界符,例如:'#$%@'。然后把所有的换行符都替换成定界符,这样相当于把代码都合并到一行。接下来查找下标最小的'//'和'/*',如果'/*'的下标更小找出在后面最近的'*/',删除掉之间所有字符;否则,找出'//'后面最近的定界符,并且删除到之间的所有字符。循环操作直到所有合法的//'和'/*'都删除掉为止,最后把定界符再替换回换行符。

代码如下:

class Solution(object):def removeComments(self, source):""":type source: List[str]:rtype: List[str]"""newLine = ''delimiter = '#$%@'for i in source:newLine += inewLine += delimiterwhile True:linecommentStart = newLine.find('//')blockCommentStart  = newLine.find('/*')if linecommentStart == -1 and blockCommentStart == -1:breakelif linecommentStart == -1:blockCommentEnd = newLine.find('*/',blockCommentStart+2)if blockCommentEnd == -1:breaknewLine = newLine[:blockCommentStart] + newLine[blockCommentEnd+2:]elif blockCommentStart == -1:linecommentEnd = newLine.find(delimiter,linecommentStart)newLine = newLine[:linecommentStart] + newLine[linecommentEnd + 4:]else:if linecommentStart < blockCommentStart:linecommentEnd = newLine.find(delimiter, linecommentStart)newLine = newLine[:linecommentStart] + newLine[linecommentEnd:]else:blockCommentEnd = newLine.find('*/', blockCommentStart + 2)if blockCommentEnd != -1:newLine = newLine[:blockCommentStart] + newLine[blockCommentEnd + 2:]else:linecommentEnd = newLine.find(delimiter, linecommentStart)newLine = newLine[:linecommentStart] + newLine[linecommentEnd:]def filterEmpty(n):return len(n) > 0return list(filter(filterEmpty, newLine.split(delimiter)))

转载于:https://www.cnblogs.com/seyjs/p/10687809.html

【leetcode】722. Remove Comments相关推荐

  1. 【LeetCode】19. Remove Nth Node From End of List

    Given a linked list, remove the nth node from the end of list and return its head. For example, Give ...

  2. 【Leetcode】2423. Remove Letter To Equalize Frequency

    题目地址: https://leetcode.com/problems/remove-letter-to-equalize-frequency/description/ 给定一个长nnn字符串sss, ...

  3. 【Leetcode】19. Remove Nth Node From End of List (cpp)

    讲思路的文章已经很多了,不再赘述,这里用的方法是两个指针一次遍历算法.想强调的是有可能要删除的就是第一个结点.删除头节点比较方便的做法是加一个伪头节点. /*** Definition for sin ...

  4. 【LeetCode】【HOT】39. 组合总和(回溯)

    [LeetCode][HOT]39. 组合总和 文章目录 [LeetCode][HOT]39. 组合总和 package hot;import java.util.ArrayList; import ...

  5. 【LeetCode 】试题总结:广度优先搜索(BFS)

    [LeetCode ]试题总结:广度优先搜索(BFS) 一.数据结构:二叉树中的 BFS (一).二叉树的堂兄弟节点 试题链接 解题思路 代码 (二).二叉树的层序遍历 II (三).二叉树的锯齿形层 ...

  6. 【LeetCode】#39组合总和(Combination Sum)

    [LeetCode]#39组合总和(Combination Sum) 加粗样式 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数 ...

  7. HOT 100(61~80)【LeetCode】

    HOT 100(61~80)[LeetCode] HHOT 100(61~80) 前言 推荐 207. 课程表[中等] 208. 实现 Trie (前缀树)[中等] 215. 数组中的第K个最大元素[ ...

  8. 【Leetcode】100. 相同的树

    题目 给定两个二叉树,编写一个函数来检验它们是否相同. 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的. 示例 1: 输入: 1 1/ \ / \2 3 2 3[1,2,3], [1 ...

  9. 【leetcode】85. Maximal Rectangle 0/1矩阵的最大全1子矩阵

    1. 题目 Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1 ...

  10. 【leetcode】486. Predict the Winner

    题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...

最新文章

  1. Dockerfile文件全面详解
  2. 全网最详细的Xshell或SecureCRT下spark-shell里出现无法退格或者删除的问题现象的解决办法(图文详解)...
  3. 雷军旗下金山云冲刺IPO:3年营收74亿,小米系贡献23%,CEO王育林仅持股2.1%
  4. Python 技术篇-连接oracle数据库并执行sql语句实例演示,python连接oracle数据库oci详细配置方法
  5. Springboot+JPA 对应关系查询时导致的堆栈溢出 :java.lang.StackOverflowError:
  6. 文章内容页调用所属栏目地址的标签
  7. linux open dev/tty0 receive_buf,书写基于内核的linux键盘纪录器(p9-0e)(3)
  8. 2012总结--第5篇--人脉篇
  9. 2个YUV视频 拼接技术
  10. R语言|ggtreeExtra包绘制进化树
  11. Chrome浏览器无法访问网页(移动硬盘)
  12. Java项目:体育用品商城(java+SpringBoot+jsp+html+maven+mysql)
  13. 想成为年薪30W+的运营,你必须具备这4个“运营思维”
  14. 管理是一门艺术,好坏全在细微之间
  15. anaconda环境安装搜不到的环境
  16. 试了一下搜狐云景对ruby的支持
  17. 1、电子负载如何用来给电池放电
  18. codeforces 577
  19. Python文件读写 w+ 与 r+ 到底如何操作
  20. oracle Blob保存方式,oracle 存储过程操作blob

热门文章

  1. Atitit session机制的实现web目录1. Sessionid的发送 11.1. session大部分情况下基于cookie实现。 11.2. 基于url的session 11.
  2. Atitit zip压缩过滤器 的模块功能语实现attilax总结 1.1. 一般可以使用webserver自带的实现,。如果实现的不好或者不好配置的,或者需要精细化控制的,可以自己使用过滤器实现。
  3. Atitti opencv2.4 实现的人脸检测 attilax总结
  4. Atitit。监听键盘上下左右方向键事件java js jquery c#.net
  5. Atitit.sql where条件表达式的原理  attilax概括
  6. Atitit.index manager api design 索引管理api设计
  7. Atitit . 编程模型的变革总结
  8. atitit.eclipse 新特性总结3.1--4.3
  9. paip.c++ 内存泄漏以及解决之道.
  10. SSH: scp 拉取云端文件到本地端