leetcode 722. Remove Comments | 722. 删除注释(Java)

x33g5p2x  于2021-11-19 转载在 Java  
字(1.1k)|赞(0)|评价(0)|浏览(269)

题目

题解

测试用例太恶心了,受不鸟啊

  1. class Solution {
  2. public static final char NO_NEW_LINE = '\'';
  3. public List<String> removeComments(String[] source) {
  4. boolean pending = false;
  5. List<String> result = new ArrayList<>();
  6. for (int i = 0; i < source.length; i++) {
  7. if (!pending) { // 左注释符已闭合
  8. int i1 = source[i].indexOf("//");
  9. if (i1 < 0) i1 = source[i].length();
  10. int i2 = source[i].indexOf("/*");
  11. if (i2 < 0) i2 = source[i].length();
  12. if (i1 == i2) { // 本行无注释
  13. add(result, source[i]);
  14. } else if (i1 < i2) { // 本行先出现//
  15. String s = source[i].substring(0, i1);
  16. add(result, s);
  17. } else { // 本行先出现/*
  18. String s = source[i].substring(0, i2);
  19. if (s.length() > 0) add(result, s + NO_NEW_LINE);
  20. source[i] = source[i].substring(i2 + 2);
  21. pending = true;
  22. i--;
  23. }
  24. } else { // 左注释符未闭合
  25. int i2 = source[i].indexOf("*/");
  26. if (i2 >= 0) {
  27. source[i] = source[i].substring(i2 + 2);
  28. pending = false;
  29. i--;
  30. }
  31. }
  32. }
  33. return result;
  34. }
  35. public void add(List<String> result, String s) {
  36. if (!result.isEmpty()) {
  37. String tail = result.get(result.size() - 1);
  38. int len = tail.length();
  39. if (tail.charAt(len - 1) == NO_NEW_LINE) { // implicit newline characters can be deleted by block comments
  40. result.set(result.size() - 1, tail.substring(0, len - 1) + s);
  41. return;
  42. }
  43. }
  44. if (s.length() > 0) result.add(s);
  45. }
  46. }

相关文章

最新文章

更多