722. Remove Comments

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;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容