LeetCode 522. Longest Uncommon Subsequence II C++

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

  1. 题目大意就是查找输入的字符串数组中查找最长的非公共子序列,非公共子序列的意思就是只要这段子序列不会出现在其他字符串中即可,不管这个长度是否是大于还是小于其他字符串,只要不存在就可以。正因为这个性质,所以题目反而简单一点,可以自己简单举个例,会发现非公共子序列最长一定是某个字符串长度,或者没有,那么我们怎么找这个字符串长度呢,我们就要分类讨论,第一种,匹配的字符串长度相等,那么我们比较是否完全一样,如果是,那么后面不用再比较了,因为不论怎样提取子序列都会出现在那个相等的字符串中,第二种,匹配的字符串长度要小,那么我们就要判断,当前这个字符串是否是它的子序列,如果是,那么后面也不用再比较了,同理,第三种,匹配的字符串长度要大,那么也不用匹配了,最长的子序列就是自己,因为后面的字符串长度都没你长,所以也就是不会出现相同的子序列,即使是子序列中的子序列。

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值