题目地址:https://leetcode.com/problems/longest-uncommon-subsequence-ii/description/

题目描述:

Given a list of strings, you need to find the longest uncommon subsequence among them. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.

Asubsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.

Theinput will be a list of strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn't exist, return -1.

Example 1:

Input: "aba", "cdc", "eae"
Output: 3

Note:

1、 Allthegivenstrings'lengthswillnotexceed10.;
2、 Thelengthofthegivenlistwillbeintherangeof[2,50].;

题目大意

找出最长非公共子序列。公共子序列的定义是一个字符串可由另一个字符串删除某些字符得到。如果在一组字符串中,某一个字符串不是任何另外的字符串的公共子序列,那么这就是它是全组的非公共子序列。找出最长的长度。

解题方法

做题多了,没想到暴力解法就能过了。

写出公共子序列的判断函数。主要是两个位置pos和i,如果能找到子字符串中的某个位置,那么就把全字符串的位置后移。

寻找最长非公共子序列的时候直接两重for循环即可,不要想太复杂。

代码如下:

class Solution(object):
    def findLUSlength(self, strs):
        """
        :type strs: List[str]
        :rtype: int
        """
        longest = -1
        _len = len(strs)
        for i in range(_len):
            issub = False
            for j in range(_len):
                if i == j:
                    continue
                if self.checkSubString(strs[i], strs[j]):
                    issub = True
                    break
            if not issub:
                longest = max(longest, len(strs[i]))
        return longest
        
    def checkSubString(self, substr, string):
        if len(substr) > len(string): return False
        if substr == string: return True
        if not substr: return True
        pos = 0
        for i in range(len(string)):
            if pos == len(substr):
                break
            if substr[pos] == string[i]:
                pos += 1
        return pos == len(substr)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

参考资料:

1、 http://www.cnblogs.com/grandyang/p/6680548.html;
2、 https://blog.csdn.net/zsensei/article/details/75227927;

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发