https://leetcode.com/problems/remove-comments/
这道题要求把C程序中的comment remove掉。
这个comments分为 // 开始的 和/* */包着的。
思路是见到 // 就跳过,见到/* 就进入comment 状态,直到遇到 */
需要定义一个状态参数 inBlock
如果在这个状态里就只找 */
如果不在这个状态里, 既要盯着//也要盯着/*
帖下代码
public List<String> removeComments(String[] source) {
List<String> result = new ArrayList<>();
boolean inBlock = false;
StringBuilder sb = new StringBuilder();
for (String str : source) {
char[] line = str.toCharArray();
int pt = 0;
while (pt < line.length) {
if (inBlock) { //只找 */
if ((pt + 1 < line.length) && line[pt] == '*' && line[pt + 1] == '/') {
pt+= 2;
inBlock = false;
} else {
pt++;
}
} else { //找 //
if (pt + 1 < line.length && line[pt] == '/' && line[pt + 1] == '/' ) {
break;
} else if (pt + 1 < line.length && line[pt] == '/' && line[pt + 1] == '*') {
// 找/*
pt+= 2;
inBlock = true;
} else {
sb.append(line[pt]);
pt++;
}
}
}
if (!inBlock && sb.length() > 0) {
result.add(sb.toString());
sb = new StringBuilder();
}
}
return result;
}