[LeetCode] Longest Uncommon Subsequence II

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.

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
class Solution {
private:
bool isSubsequence(string& s1, string& s2) {
int i, j;
for(i = 0, j = 0; i < s1.length() && j < s2.length(); j++)
if(s1[i] == s2[j])
++i;
return i == s1.length();
}
public:
int findLUSlength(vector<string>& strs) {
vector<bool> table(strs.size(), true);
sort(strs.begin(), strs.end(), [](string& a, string&b) { return a.length() == b.length() ? a < b : a.length() < b.length();});
for(int i = strs.size() - 1; i >= 0; --i) {
bool flag = true;
for(int j = strs.size() - 1; j >= 0; --j) {
if(i == j) continue;
if(isSubsequence(strs[i], strs[j])) {
flag = false;
break;
}
}
if(flag)
return strs[i].length();
}

return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/02/PS/LeetCode/longest-uncommon-subsequence-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.