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

};
相关推荐
lifloveyou39 分钟前
table接口结构
python
8Qi81 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
888CC++2 小时前
如何在 C 语言中进行程序调试?
前端·javascript·算法
Warson_L2 小时前
class 扩展
python
前端与小赵3 小时前
Python 数据结构陷阱与复数运算优化:列表、元组、字典成员操作辨析及 NumPy 高效实践
python
天天进步20153 小时前
Python全栈项目--基于深度学习的视频目标跟踪系统
python·深度学习·音视频
天天进步20154 小时前
Python全栈项目--Python自动化运维工具开发
运维·python·自动化
(●—●)橘子……4 小时前
力扣第503场周赛练习理解
python·学习·算法·leetcode·职场和发展·周赛
爱吃羊的老虎4 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python