zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    springboot自定义消息转换器HttpMessageConverter
    fastJson的feature和SerializerFeature属性的解释
    ThreadLocal
    复习面向对象 -- 继承
    复习面向对象--创建对象
    js实现二分查找算法
    SVN问题解决--Attempted to lock an already-locked dir
    封装cookie设置和获取的简易方法
    JS判断客户端是否是iOS或者Android手机移动端(转载)
    【Vue笔记】-- 详解vue生命周期
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/13769029.html
Copyright © 2011-2022 走看看