leetcode_522最长特殊序列

522. 最长特殊序列 II

难度中等121

给定字符串列表 strs ,返回其中 最长的特殊序列 。如果最长特殊序列不存在,返回 -1

特殊序列 定义如下:该序列为某字符串 独有的子序列(即不能是其他字符串的子序列)

s子序列可以通过删去字符串 s 中的某些字符实现。

  • 例如,"abc""aebdc" 的子序列,因为您可以删除"aebdc"中的下划线字符来得到 "abc""aebdc"的子序列还包括"aebdc""aeb" 和 “” (空字符串)。

示例 1:

输入: strs = ["aba","cdc","eae"]
输出: 3

示例 2:

输入: strs = ["aaa","aaa","aa"]
输出: -1

提示:

  • 2 <= strs.length <= 50
  • 1 <= strs[i].length <= 10
  • strs[i] 只包含小写英文字母

//题目要求即找到最长特殊子串返回子串长度(这个字串可以是字符串自己)

//特殊意味着不是其他字符串的子串

因此编写判断字串的函数

再对strs这个字符串序列进行遍历,找到所有不是其他字符串子串的字符串的最大长度返回

#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class solution
{

public:
    int findLUSlength(vector<string> &strs)
    {
        int ans = -1;
        int n = strs.size();
        for (int i = 0; i < n; i++)
        {
            bool judge = true;
            for (int j = 0; j < n; j++)
            {
                if (i != j && check(strs[i], strs[j]))
                {
                    judge = false;
                    break;
                }
            }
            if (judge)
            {
                ans = max(ans, static_cast<int>(strs[i].size())); //这里必须类型强制转换,不然无法使用max函数
            }
        }
    }

    bool check(string str1, string str2) //判断str1是否为str2子串
    {
        int i = 0; // str1长度短
        int j = 0; // str2长度长
        while (i < str1.size() && j < str2.size())
        {
            if (str1[i] == str2[j])
            {
                i++;
                j++;
            }
            else
            {
                j++;
            }
        }
        return i == str1.size();
    }
};

int main()
{
    vector<string> strs;
    strs.push_back("def"); //把字符串"def"压进容器
    cout << strs[0].size() << endl;
    cout << typeid(strs[0].size()).name() << endl;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怀旧小ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值