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

};
相关推荐
Python×CATIA工业智造31 分钟前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco1 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
森焱森2 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
狐凄2 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊3 小时前
Python之--基本知识
开发语言·前端·python
QuantumStack3 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客4 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠4 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
笑稀了的野生俊4 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva4 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm