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

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

题目

题解

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

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);
    }
}

相关文章

微信公众号

最新文章

更多