LeetCode 521. 最长特殊序列 Ⅰ(C、C++、python)

给定两个字符串,你需要从这两个字符串中找出最长的特殊序列。最长特殊序列定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。

子序列可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。

输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。

示例 :

输入: "aba", "cdc"
输出: 3
解析: 最长特殊序列可为 "aba" (或 "cdc")

说明:

两个字符串长度均小于100。

字符串中的字符仅含有 'a'~'z'。

C

int findLUSlength(char* a, char* b) 
{
    int m=strlen(a);
    int n=strlen(b);
    int res;
    if(m!=n)
    {
        res=m>n?m:n;
    }
    else
    {
        int i;
        for(i=0;i<m;i++)
        {
            if(a[i]!=b[i])
            {
                res=m;
                break;
            }
        }
        if(m==i)
        {
            res=-1;
        }        
    }
    return res;
}

C++

class Solution {
public:
    int findLUSlength(string a, string b) 
    {
        int m=a.length();
        int n=b.length();
        int res;
        if(m!=n)
        {
            res=max(m,n);
        }
        else
        {
            if(a==b)
            {
                res=-1;
            }
            else
            {
                res=m;
            }            
        }
        return res;
    }
};

python

class Solution:
    def findLUSlength(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: int
        """
        m=len(a)
        n=len(b)
        if m!=n:
            res=max(m,n)
        else:
            if a==b:
                res=-1
            else:
                res=m
        return res

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/84405185