每日一题(722. 删除注释)-模拟操作

题目

722. 删除注释

题解思路

c++中

	//注释为该行内容不显示
	/*  */ 为这部分内容不显示

定义标记为flag 当遇到"/"时, 代表有注释内容

  • 若后面紧跟着"/",则直接退出循环
  • 若后面跟着"*", 则寻找注释结尾

代码

C++

class Solution {
public:
    vector<string> removeComments(vector<string>& source) {
        int n = source.size();
        vector<string> res;
        string temp = "";
        bool flag = false;
        for(auto &word : source){
            for(int i = 0; i < word.size(); ++i){
                if (flag){
                    if (i + 1 < word.size() && word[i] == '*' && word[i + 1] == '/'){
                        flag = false;
                        ++i;
                    }
                }else{
                    if (i + 1 < word.size() && word[i] == '/' && word[i + 1] == '*'){
                        flag = true;
                        ++i;
                    }else if(i + 1 < word.size() && word[i] == '/' && word[i + 1] == '/'){
                        break;
                    }else{
                        temp += word[i];
                    }
                }
            }
            if( !flag && temp != "") {
                res.push_back(temp);
                temp = "";
            }
        }
        return res;
    }
};

Python

class Solution:
    def removeComments(self, source: List[str]) -> List[str]:
        res = []
        temp = []
        flag = False 
        for word in source:
            i = 0
            while i < len(word):
                if flag:
                    while i + 1< len(word) and word[i] == '*' and word[i + 1] == "/":
                        flag = False
                        i += 1
                else:
                    if i + 1 < len(word) and word[i] == '/' and word[i + 1] == "*":
                        flag = True
                        i += 1
                    elif i + 1 < len(word) and word[i] == '/' and word[i + 1] == '/':
                        break
                    else:
                        temp.append(word[i])
                i += 1
            if not flag and len(temp) > 0:
                res.append("".join(temp))
                temp = []
        return res

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值