522. Longest Uncommon Subsequence II

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.

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

Solution:

思路:
首先我们给字符串按长度降序排序
然后我们用一个set记录字符串,来加速判断是否有相同的
然后我们开始遍历字符串(length由大到小),对于当前遍历到的字符串:
(1) set中判断是否有相同的字符串,有的话continue
(2) 判断是否是比它长的str的subsequence
都不是的话 则返回这个的length
Time Complexity: O(NlogN) Space Complexity: O(N)

Solution Code:

class Solution {
    public int findLUSlength(String[] strs) {
        /*
        Arrays.sort(strs, new Comparator() {
            public int compare(String o1, String o2) {
                return o2.length() - o1.length();
            }
        });
        */
        
        // 按长度降序排列
        Arrays.sort(strs, (o1, o2) -> o2.length() - o1.length());
        
        
        Set duplicates = getDuplicates(strs);
        for(int i = 0; i < strs.length; i++) {
            if(!duplicates.contains(strs[i])) {
                if(i == 0) return strs[0].length(); //最长的可以直接return
                for(int j = 0; j < i; j++) { //其余的需要和比它长的str比一下,看是否不比它长的str的subsequence
                    if(isSubsequence(strs[j], strs[i])) break;
                    if(j == i-1) return strs[i].length(); // 都不是的话
                }
            }
        }
        return -1;
    }
    
    public boolean isSubsequence(String a, String b) {
        int i = 0, j = 0;
        while(i < a.length() && j < b.length()) {
            if(a.charAt(i) == b.charAt(j)) j++;
            i++;
        }
        return j == b.length();
    }
    
    private Set getDuplicates(String[] strs) {
        Set set = new HashSet();
        Set duplicates = new HashSet();
        for(String s : strs) {
            if(set.contains(s)) duplicates.add(s);
            set.add(s);
        }
        return duplicates;
    }
}

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