1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| class Solution { public List<String> removeComments(String[] source) { List<String> resultList = new ArrayList<>();
boolean inBlockComment = false; StringBuilder sb = new StringBuilder(80); for (String line : source) { for (int i = 0; i < line.length(); i++) { char c = line.charAt(i);
if (inBlockComment) { if (c == '*' && i + 1 < line.length() && line.charAt(i + 1) == '/') { inBlockComment = false; i++; } } else if (c == '/' && i + 1 < line.length()) { char nextC = line.charAt(i + 1); if (nextC == '/') { break; } else if (nextC == '*') { inBlockComment = true; i++; } else { sb.append(c); } } else { sb.append(c); } }
if (sb.length() > 0 && !inBlockComment) { resultList.add(sb.toString()); sb.setLength(0); } }
return resultList; } }
|