# 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:

``````Input: "aba", "cdc", "eae"
Output: 3
``````

Note:

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

``````class Solution {
public:
int findLUSlength(vector<string>& strs) {
int res = -1, j = 0, n = strs.size();
for (int i = 0; i < n; ++i) {
for (j = 0; j < n; ++j) {
if (i == j) continue;
if (checkSubs(strs[i], strs[j])) break;
}
if (j == n) res = max(res, (int)strs[i].size());
}
return res;
}
int checkSubs(string subs, string str) {
int i = 0;
for (char c : str) {
if (c == subs[i]) ++i;
if (i == subs.size()) break;
}
return i == subs.size();
}
};
``````

``````class Solution {
public:
int findLUSlength(vector<string>& strs) {
int n = strs.size();
unordered_set<string> s;
sort(strs.begin(), strs.end(), [](string a, string b){
if (a.size() == b.size()) return a > b;
return a.size() > b.size();
});
for (int i = 0; i < n; ++i) {
if (i == n - 1 || strs[i] != strs[i + 1]) {
bool found = true;
for (auto a : s) {
int j = 0;
for (char c : a) {
if (c == strs[i][j]) ++j;
if (j == strs[i].size()) break;
}
if (j == strs[i].size()) {
found = false;
break;
}
}
if (found) return strs[i].size();
}
s.insert(strs[i]);
}
return -1;
}
};
``````

Longest Uncommon Subsequence I

https://discuss.leetcode.com/topic/85033/checking-subsequence-without-hashing

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation