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:
- All the given strings’ lengths will not exceed 10.
- The length of the given list will be in the range of [2, 50].
Approach
- 题目大意就是查找输入的字符串数组中查找最长的非公共子序列,非公共子序列的意思就是只要这段子序列不会出现在其他字符串中即可,不管这个长度是否是大于还是小于其他字符串,只要不存在就可以。正因为这个性质,所以题目反而简单一点,可以自己简单举个例,会发现非公共子序列最长一定是某个字符串长度,或者没有,那么我们怎么找这个字符串长度呢,我们就要分类讨论,第一种,匹配的字符串长度相等,那么我们比较是否完全一样,如果是,那么后面不用再比较了,因为不论怎样提取子序列都会出现在那个相等的字符串中,第二种,匹配的字符串长度要小,那么我们就要判断,当前这个字符串是否是它的子序列,如果是,那么后面也不用再比较了,同理,第三种,匹配的字符串长度要大,那么也不用匹配了,最长的子序列就是自己,因为后面的字符串长度都没你长,所以也就是不会出现相同的子序列,即使是子序列中的子序列。
Code
class Solution {
public:
static bool cmp(const string &a, const string &b) {
return a.size() > b.size();
}
bool issubsequence(string a, string b) {
int i = 0, j = 0;
while (i < a.size() && j < b.size()) {
if (a[i] == b[j]) {
i++;
}
j++;
}
return i == a.size();
}
int findLUSlength(vector<string>& strs) {
int n = strs.size();
sort(strs.begin(), strs.end(), cmp);
for (int i = 0; i < n; i++) {
int maxn = strs[i].size();
for (int j = 0; j < n; j++) {
if (i == j)continue;
if (strs[i].size() == strs[j].size()) {
if (strs[i].compare(strs[j]) == 0) {
maxn = 0;
break;
}
}
else if (strs[i].size() < strs[j].size()) {
if (issubsequence(strs[i], strs[j])) {
maxn = 0;
break;
}
}
else {
break;
}
}
if (maxn != 0)return maxn;
}
return -1;
}
};