力扣题:子序列-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();
    }

};
相关推荐
月光船幽幽11 小时前
真实即粗糙,光滑是伪造
人工智能·python
一次旅行11 小时前
Attention机制从数学到工程:拆解缩放点积+多头注意力|附可运行PyTorch实现与踩坑指南
人工智能·pytorch·python
泡干脆面就番茄11 小时前
NumPy 科学计算完全指南:从数组创建到广播机制
python·numpy
denggun1234511 小时前
信号量(DispatchSemaphore vs AsyncSemaphore)、swift协作式线程池 and python信号量
开发语言·python·swift
起光11 小时前
Python类与对象(一)
python
阿童木写作11 小时前
跨马翻译:AI批量图片翻译工具,视频字幕翻译与智能抠图一站式解决
大数据·人工智能·python·音视频
Zane199411 小时前
只改一个方向的引用,循环引用就能立刻被回收?一文讲透 weakref 弱引用
后端·python
陈年老古董12 小时前
OpenCV图像处理笔记:图像拼接、答题卡识别与目标提取
人工智能·笔记·python·opencv·计算机视觉
CTA终结者12 小时前
2026年程序员量化开发学习:用示例、拆解和练习入门
人工智能·python