【Lintcode】1902. Find Google
阿新 • • 發佈:2020-12-10
題目地址:
https://www.lintcode.com/problem/find-google/description
給定一個字串陣列形式的C++檔案,每一行是個字串。問該字串的註釋裡是否含字串"Google"
。註釋有兩種,"//"
代表單行註釋,即本行從它開始向後都是註釋;"/*"
和"*/"
括起來的是多行註釋,可以跨行,被包圍起來的都是註釋。
對於每行,我們都尋找一下"//"
,"/*"
,"*/"
,"Google"
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是最長字串長度。