• 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/

  • 相关阅读:
    .htaccess的基本用法与介绍
    SEO之如何做301转向
    HTML的display属性将行内元素、块状元素、行内块状元素互相转换以及三者的区别
    web前端利用HTML代码显示符号
    Day 54 Django_模型层_用户认证&中间件
    Day 53 Django_模型层_forms组件$cookie与session
    Day 52 Django_模型层_Ajax&分页器
    Day 51 Django_模型层_多表操作
    Day 50 Django_模型层_ORM&单表操作
    Day 49 Django_模板层
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/13769029.html
Copyright © 2020-2023  润新知