【Lintcode】1902. Find Google

题目地址:

https://www.lintcode.com/problem/find-google/description

给定一个字符串数组形式的C++文件,每一行是个字符串。问该字符串的注释里是否含字符串"Google"。注释有两种,"//"代表单行注释,即本行从它开始向后都是注释;"/*""*/"括起来的是多行注释,可以跨行,被包围起来的都是注释。

对于每行,我们都寻找一下"//""/*""*/""Google"这几个字符串的位置(直接用java的API来找,找到返回下标,找不到返回 − 1 -1 1),然后分类讨论:
1、如果"//"的位置在"Google"的前面(即下标小于),那直接返回true(这里考虑了 − 1 -1 1的情况);
2、接下来考虑"/*""*/"的存在情况。如果两者都存在并且"Google"夹在中间,则返回true;如果只有"/*"存在并且"/*"的位置小于"Google"则也返回true;如果只有"*/"存在,并且"Google"存在并且位置小于"*/"也返回true;如果都不存在,这时候要判断最近的上一次"/*"出现的行数是不是小于当前行,并且没有被"*/"包裹,如果是,则返回true;
3、最后循环退出了则返回false;

代码如下:

import java.util.List;

public class Solution {
    /**
     * @param S: The c++ file
     * @return: return if there is "Google" in commet line
     */
    public boolean FindGoogle(List<String> S) {
        // Write your code here.
        int last = -1;
        for (int i = 0; i < S.size(); i++) {
            String s = S.get(i);
            int a = s.indexOf("//"), b = s.indexOf("Google"), c = s.indexOf("/*"), d = s.indexOf("*/");
            if (a != -1 && a < b) {
                return true;
            }
            
            if (c != -1 && (a > c || a == -1)) {
                last = i;
            }
            
            if (b != -1) {
                if (c != -1 && d != -1) {
                    if (c < b && b < d) {
                        return true;
                    }
                } else if (c != -1) {
                    if (c < b) {
                        return true;
                    }
                } else if (d != -1) {
                    if (b < d) {
                        return true;
                    }
                } else {
                    if (last != -1 && last < i) {
                        return true;
                    }
                }
            }
            
            if (d != -1) {
                last = -1;
            }
        }
        
        return false;
    }
}

时间复杂度 O ( n l ) O(nl) O(nl) n n n是字符串数量, l l l是最长字符串长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值