LC.P522[最长特殊序列II]

方法一:贪心+双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int findLUSlength(String[] strs) {
int n = strs.length, ans = -1;
for (int i = 0; i < n; ++i) {
boolean flag = true;
for (int j = 0; j < n; ++j) {
if (i != j && isSubseq(strs[i], strs[j])) {
flag = false;
break;
}
}
if (flag) ans = Math.max(ans, strs[i].length());
}
return ans;
}

private boolean isSubseq(String s, String t) {
int i = 0, j = 0;
while (i < s.length() && j < t.length()) {
if (s.charAt(i) == t.charAt(j)) ++i;
++j;
}
return i == s.length();
}
}
  • 时间复杂度:$O(n^2 \times l)$,其中$l$为字符串的平均长度
  • 空间复杂度:$O(1)$