522. Longest Uncommon Subsequence II

Description

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.

A subsequence 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.

The input 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. All the given strings' lengths will not exceed 10.
  2. The length of the given list will be in the range of [2, 50].

Solution

Sort and compare, O(n ^ 2 * m), S(1)

n is string count, m is average length of string

在"Longest Uncommon Subsequence I"的基础上,将2个扩展成n个string。思路还是一样的,想来想去没有什么特别的办法,还是得两两比较是否是isSubsequence。

一个优化是将strs[]按照string length倒序排列。这样能保证第一个找个到的uncommon subsequence即为最长的。

class Solution {
    public int findLUSlength(String[] strs) {
        if (strs == null || strs.length == 0) {
            return -1;
        }
        // sort by length desc order
        Arrays.sort(strs, (a, b) -> b.length() - a.length());
        
        for (int i = 0; i < strs.length; ++i) {
            boolean found = true;
            
            for (int j = 0; j < strs.length; ++j) {
                if (i == j) {   // don't compare with itself
                    continue;
                }
                
                if (isSubsequence(strs[i], strs[j])) {
                    found = false;
                    break;
                }
            }
            
            if (found) {
                return strs[i].length();
            }
        }
        
        return -1;
    }
    // return if t is subsequence of s
    private boolean isSubsequence(String t, String s) {
        if (t.length() > s.length()) {
            return false;
        } else if (t.equals(s)) {
            return true;
        }
        
        int i = 0;
        for (int j = 0; j < s.length() && i < t.length(); ++j) {
            if (t.charAt(i) == s.charAt(j)) {
                ++i;
            }
        }
        
        return i == t.length();
    }
}

你可能感兴趣的:(522. Longest Uncommon Subsequence II)