题目地址:
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是最长字符串长度。