测试用例太恶心了,受不鸟啊
class Solution {
public static final char NO_NEW_LINE = '\'';
public List<String> removeComments(String[] source) {
boolean pending = false;
List<String> result = new ArrayList<>();
for (int i = 0; i < source.length; i++) {
if (!pending) { // 左注释符已闭合
int i1 = source[i].indexOf("//");
if (i1 < 0) i1 = source[i].length();
int i2 = source[i].indexOf("/*");
if (i2 < 0) i2 = source[i].length();
if (i1 == i2) { // 本行无注释
add(result, source[i]);
} else if (i1 < i2) { // 本行先出现//
String s = source[i].substring(0, i1);
add(result, s);
} else { // 本行先出现/*
String s = source[i].substring(0, i2);
if (s.length() > 0) add(result, s + NO_NEW_LINE);
source[i] = source[i].substring(i2 + 2);
pending = true;
i--;
}
} else { // 左注释符未闭合
int i2 = source[i].indexOf("*/");
if (i2 >= 0) {
source[i] = source[i].substring(i2 + 2);
pending = false;
i--;
}
}
}
return result;
}
public void add(List<String> result, String s) {
if (!result.isEmpty()) {
String tail = result.get(result.size() - 1);
int len = tail.length();
if (tail.charAt(len - 1) == NO_NEW_LINE) { // implicit newline characters can be deleted by block comments
result.set(result.size() - 1, tail.substring(0, len - 1) + s);
return;
}
}
if (s.length() > 0) result.add(s);
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/sinat_42483341/article/details/121418030
内容来源于网络,如有侵权,请联系作者删除!