Leetcode 522. Longest Uncommon Subsequence II
Given a list of strings, you need to find the longest string that is an uncommon subsequence among the given strings. An uncommon subsequence is a string that is a subsequence of one string but not of any other string. If no such string exists, return -1.
A subsequence is a sequence derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
strs
.#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool isSubsequence(const string& a, const string& b) {
int n = a.size(), m = b.size();
int i = 0, j = 0;
while (i < n && j < m) {
if (a[i] == b[j]) {
i++;
}
j++;
}
return i == n;
}
int findLUSlength(vector<string>& strs) {
sort(strs.begin(), strs.end(), [](const string& a, const string& b) {
return a.size() > b.size();
});
for (int i = 0; i < strs.size(); ++i) {
bool isUncommon = true;
for (int j = 0; j < strs.size(); ++j) {
if (i != j && isSubsequence(strs[i], strs[j])) {
isUncommon = false;
break;
}
}
if (isUncommon) {
return strs[i].size();
}
}
return -1;
}
int main() {
vector<string> strs = {"aba", "cdc", "eae"};
cout << findLUSlength(strs) << endl;
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?