522. Longest Uncommon Subsequence II

Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

The input will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn’t exist, return -1.

Example 1:

1
2
Input: "aba", "cdc", "eae"
Output: 3

Note:

All the given strings’ lengths will not exceed 10.
The length of the given list will be in the range of [2, 50].

解法1:O(N^2 * X)

x is the average length of strings. N is the number of strings
这题的关键在于substring的定义要注意,和平时遇到的substring定义不同。
这里的substring是可以提取不连续的字符组成。
分析一下可以发现,如果存在答案的话,那么uncommon subsequence 一定是其中某一个string,那么就把每一个string和其他的相比,看是否为其他的substring,如果不是,那么更新最大值。

C++

1

Java

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
public class Solution {
public int findLUSlength(String[] strs) {
int j = 0;
int res = -1;
for (int i = 0; i < strs.length; i++) {
for (j = 0; j < strs.length; j++) {
if (j != i) {
if (isSubString(strs[i], strs[j])) {
break;
}
}
}
if (j == strs.length) {
res = Math.max(res, strs[i].length());
}
}
return res;
}
private boolean isSubString(String x, String y) {
// By definition, the substring can be derived by deleting some characters
int j = 0;
for (int i = 0; i < y.length() && j < x.length(); i++)
if (x.charAt(j) == y.charAt(i))
j++;
return j == x.length();
}
}