问题描述
给定一个源代码文件,该文件中的注释需要被移除。注释可能是单行的,也可能是多行的。你需要实现一个函数来移除这些注释,并返回移除注释后的代码。
输入
输入是一个字符串数组 source
,其中每个字符串代表源代码中的一行。
输出
返回一个字符串数组,其中每个字符串代表移除注释后的代码行。
示例
示例 1:
输入: source = ["/*Test program */", "int main()", "{ /* keh*/ int i = 10;", "/* test */"]
输出: [" int main()", "{ int i = 10;", ""]
示例 2:
输入: source = ["// This is a single line comment", "int main()", "/* multi line comment", "* multi-line comment */", "int i = 10;"]
输出: ["", "int main()", "", "", "int i = 10;"]
解法一
解题思路:
我们需要遍历每一行代码,判断并移除单行和多行注释。对于单行注释,我们找到//
并移除其后面的所有字符。对于多行注释,我们需要找到/*
和*/
,并移除它们之间的所有字符。
/** @lc app=leetcode.cn id=722 lang=javascript** [722] Remove Comments*/// @lc code=start
function removeComments(source) {const result = [];let blockComment = false;for (let line of source) {let i = 0;while (i < line.length) {if (!blockComment && i + 1 < line.length && line[i] === '/' && line[i + 1] === '/') {line = line.substring(0, i);break;} else if (!blockComment && i + 1 < line.length && line[i] === '/' && line[i + 1] === '*') {line = line.substring(0, i);blockComment = true;i--;} else if (blockComment && i + 1 < line.length && line[i] === '*' && line[i + 1] === '/') {line = line.substring(0, i) + line.substring(i + 2);blockComment = false;i--;}i++;}result.push(line);}return result;
}
// @lc code=end