题目原址
https://leetcode.com/problems/remove-comments/description/
题目描述
给定一段代码段,其中包括注释部分,注释分为两种个://
和/* */
,现要求将代码段中的注释部分删除返回只有有效代码部分
如:输入source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
上述输入即:
/*Test program */
int main()
{
// variable declaration
int a, b, c;
/* This is a test
multiline
comment for
testing */
a = b + c;
}
要求输出为:
"int main()","{ "," ","int a, b, c;","a = b + c;","}"
即:
int main()
{
int a, b, c;
a = b + c;
}
解题思路
注意//
只能注释一行,而/*
则可以注释从其开始到*/
的部分,所以对于两种个不同的注释处理的方式应该不同。而且注意注释可能不是单独的一行,可能是再有效代码行后面加入一行注释或者多行注释。
- 首先设置一个标识位,用来标识当前行前面是否有
/*
,如果有,则在/*
后面的值和*/
之前的值都是注释,需要将其刨除
AC代码
class Solution {
public List<String> removeComments(String[] source) {
List<String> ret = new ArrayList<>();
StringBuilder sb = new StringBuilder();
int row = 0, col = 0;
boolean comment = false;
while(row < source.length) {
//comment如果为true,表明当前行前面有/*
if(comment) {
//找到代码中*/的位置,并将该位置放在index变量中
int index = source[row].indexOf("*/", col);
//如果index = -1说明当前行没有*/,则将行数row+1,将下一行的起始下标置0
if(index == -1) {
row ++;
col = 0;
//如果index的值不为-1,则说明当前行找到了*/ 则将代码行的有效代码下标置为index+2。及那个comment置为false
}else {
comment = false;
col = index + 2;
}
}else{
//获取当前行/*的下标
int index1 = source[row].indexOf("/*", col);
//获取当前行//的下标
int index2 = source[row].indexOf("//", col);
//如果index1 = -1说明,当前行没有/*,则正行都是有效代码,将其长度放在index1中
if(index1 == -1)
index1 = source[row].length();
//如果index2 = -1说明,当前行没有//,则正行都是有效代码,将其长度放在index2中
if(index2 == -1)
index2 = source[row].length();
//把非评论部分放入
for(int i = col; i < Math.min(index1, index2); i++) {
sb.append(source[row].charAt(i));
}
//这里比较//和/*第一次出现的位置,如果//在/*前面出现,就说明该行是被//注释的,否则是被/*注释的
if(index2 <= index1) {
if(sb.length() > 0) {
ret.add(new String(sb));
sb.setLength(0);
}
row ++;
col = 0;
}else{
comment = true;
col = index1 +2;
}
}
}
return ret;
}
}