522. Longest Uncommon Subsequence 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public int findLUSlength(String[] strs) {
// 注意转换题意,如果一个序列为某字符串独有的子序列,那么最长的特殊序列一定为该序列所属的字符串

int maxLength = -1;

for (int i = 0; i < strs.length; i++) {
if (strs[i].length() < maxLength) {
continue;
}

boolean special = true;
for (int j = 0; j < strs.length; j++) {
if (i == j) {
continue;
}
if (isSubSequence(strs[i], strs[j])) {
// 如果是其他字符串的子序列,则不是特殊序列
special = false;
break;
}
}

if (special) {
maxLength = Math.max(maxLength, strs[i].length());
}
}

return maxLength;
}

private boolean isSubSequence(String strA, String strB) {
int m = strA.length(), n = strB.length();

if (strB.length() < strA.length()) {
return false;
}

int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (strA.charAt(i - 1) == strB.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}

return dp[m][n] == strA.length();
}
}

References

522. Longest Uncommon Subsequence II