其他分享
首页 > 其他分享> > LeetCode 722. Remove Comments (删除注释)

LeetCode 722. Remove Comments (删除注释)

作者:互联网

题目标签:String

  遍历这一行中的每一个char,

    如果遇到 //  直接跳过这一行剩下的chars;

    如果遇到 /* 需要一个 flag 来保存 in block 的状态,直到遇到 */

    其他情况下,保存char

  当不在 /* */ block 的状态中:保存这一行 到list中。

  具体看code。

 

 

Java Solution: 

Runtime:  0 ms, faster than 100.00 % 

Memory Usage: 37.3 MB, less than 98.63 %

完成日期:09/27/2020

关键点:建立一个flag 保存 /* */ 状态

class Solution {
    public List<String> removeComments(String[] source) {
        boolean inBlock = false;
        StringBuilder newline = new StringBuilder();
        List<String> ans = new ArrayList();
        
        for (String line: source) {
            int i = 0;
            char[] chars = line.toCharArray();
            
            if (!inBlock)
                newline = new StringBuilder();
            
            // go through each char of line
            while (i < line.length()) {
                // if find the "/*", change flag and keep moving
                if (!inBlock && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '*') {
                    inBlock = true;
                    i++;
                }
                // find the "*/", change flag back and keep moving
                else if (inBlock && i+1 < line.length() && chars[i] == '*' && chars[i+1] == '/') {
                    inBlock = false;
                    i++;
                }
                // find the "//", skip the rest of this line.
                else if (!inBlock && i+1 < line.length() && chars[i] == '/' && chars[i+1] == '/') {
                    break;
                }
                // only save char when it is not in /* */ block 
                else if (!inBlock) {
                    newline.append(chars[i]);
                }
                i++;
            }
            
            // if not in /* */ block, add the line into list
            if (!inBlock && newline.length() > 0) {
                ans.add(new String(newline));
            }
        }
        return ans;
    }
}

参考资料:https://leetcode.com/problems/remove-comments/solution/

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

标签:inBlock,chars,Remove,char,length,722,Comments,&&,line
来源: https://www.cnblogs.com/jimmycheng/p/13769029.html