力扣题:子序列-12.29

力扣题-12.29

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:522. 最长特殊序列 II

解题思想:首先将字符串列表按长度进行降序,然后对每个字符串进行判断是否是独有的子序列,因为短的字串可能是长的字串的子序列,但是长的字串肯定是短字串的独有的子序列,通过这个条件进行判断。

python 复制代码
class Solution(object):
    def findLUSlength(self, strs):
        """
        :type strs: List[str]
        :rtype: int
        """
        strs.sort(key=len,reverse=True)
        for i in range(0,len(strs)):
            if not self.isSubSeqOfAnother(strs,i):
                return len(strs[i])
        return -1

    ## 检查给定索引(idx)处的字符串是否是列表中任何其他字符串的子序列。
    def isSubSeqOfAnother(self,strs,idx):
        for i in range(0,len(strs)):
            if i==idx:
                continue
            ## 判断到小于时之后的可以不用判断了
            if len(strs[i])<len(strs[idx]):
                break
            ## 判断是否是子序列
            if self.isSubSeq(strs[idx],strs[i]):
                return True
        return False

    ## 判断s1是否为s2的子序列
    def isSubSeq(self,s1,s2):
        p1,p2=0,0
        while p1<len(s1) and p2<len(s2):
            while p2<len(s2) and s2[p2]!=s1[p1]:
                p2+=1
            if p2<len(s2):
                p1+=1
            p2+=1
        return p1==len(s1)
cpp 复制代码
class Solution {
public:
    int findLUSlength(vector<string>& strs) {
        std::sort(strs.begin(), strs.end(), [](const std::string& a, const std::string& b) {
            return a.length() > b.length();
        });
        for (int i = 0; i < strs.size(); ++i) {
            if (!isSubSeqOfAnother(strs, i)) {
                return strs[i].length();
            }
        }

        return -1;
    }
    bool isSubSeqOfAnother(vector<string>& strs,int idx){
        for(int i=0;i<strs.size();i++){
            if(i == idx){
                continue;
            }
            if(strs[i].length()<strs[idx].length()){
                break;
            }
            if(isSubSeq(strs[idx],strs[i])){
                return true;
            }
        }
        return false;
    }
    bool isSubSeq(string s1,string s2){
        int p1 = 0, p2 = 0;
        while(p1<s1.length() && p2<s2.length()){
            while(p2<s2.length() && s2[p2]!=s1[p1]){
                p2++;
            }
            if(p2<s2.length()){
                p1++;
            }
            p2++;
        }
        return p1==s1.length();
    }

};
相关推荐
纪元A梦35 分钟前
贪心算法应用:化工反应器调度问题详解
算法·贪心算法
深圳市快瞳科技有限公司1 小时前
小场景大市场:猫狗识别算法在宠物智能设备中的应用
算法·计算机视觉·宠物
liulilittle1 小时前
OPENPPP2 —— IP标准校验和算法深度剖析:从原理到SSE2优化实现
网络·c++·网络协议·tcp/ip·算法·ip·通信
一个天蝎座 白勺 程序猿2 小时前
Python爬虫(47)Python异步爬虫与K8S弹性伸缩:构建百万级并发数据采集引擎
爬虫·python·kubernetes
XiaoMu_0013 小时前
基于Django+Vue3+YOLO的智能气象检测系统
python·yolo·django
superlls4 小时前
(算法 哈希表)【LeetCode 349】两个数组的交集 思路笔记自留
java·数据结构·算法
honder试试4 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
田里的水稻4 小时前
C++_队列编码实例,从末端添加对象,同时把头部的对象剔除掉,中的队列长度为设置长度NUM_OBJ
java·c++·算法
心本无晴.4 小时前
Python进程,线程
python·进程
纪元A梦4 小时前
贪心算法应用:保险理赔调度问题详解
算法·贪心算法