题目描述
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.
样例
Input: "aba", "cdc", "eae"
Output: 3
算法1
$O(n^2 * m)$
设答案是字符串str
的一个子序列,长度是x
,
如果x != str.size()
那么我把剩下的字符串贴上去,也是答案。
所以答案就是该字符串的长度 或者是 -1
。
C++ 代码
class Solution {
public:
bool subString(string a, string b) {
int n = a.size();
int m = b.size();
int i = 0;
int j = 0;
while (i < n && j < m) {
if (a[i] == b[j]) {
i ++;
j ++;
}
else {
i ++;
}
}
return j == m;
}
int findLUSlength(vector<string>& strs) {
int n = strs.size();
vector<vector<bool>> In(n + 1, vector<bool> (n + 1, 0));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
In[i][j] = subString(strs[i], strs[j]);
}
}
int ans = -1;
for (int i = 0; i < n; ++i) {
bool ok = true;
for (int j = 0; j < n; ++j) {
if (i == j) continue;
if (In[j][i]) {
ok = false;
break;
}
}
if (ok) {
ans = max(ans, int(strs[i].size()));
}
}
return ans;
}
};