最长非公共子序列(既不相同也不重复)Longest Uncommon Subsequence II

纵饮孤独 提交于 2020-03-02 15:27:28

问题:

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.

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].

解决:

①  暴力解决。遍历所有的字符串,对于每个遍历到的字符串,再和所有的其他的字符串比较,看是不是某一个字符串的子序列,如果都不是的话,那么当前字符串就是一个非共同子序列,用其长度来更新结果res。

class Solution { //11ms
    public int findLUSlength(String[] strs) {
        int res = -1;
        int j = 0;
        int len = strs.length;
        for (int i = 0;i < len;i ++){
            for (j = 0;j < len;j ++){
                if (i == j) continue;
                if (isSubs(strs[i],strs[j])) break;
            }
            if (j == len) res = Math.max(res,strs[i].length());
        }
        return res;
    }
    public boolean isSubs(String subs,String str){
        int i = 0;
        for (char c : str.toCharArray()){
            if (c == subs.charAt(i)) i ++;
            if (i == subs.length()) break;
        }
        return i == subs.length();
    }
}

② 按照字符串长度降序排列strs;遍历strs,如果str不是所有strs的独有子字符串,返回str的长度;如果没有找到独有字符串,返回-1。

class Solution { //12ms
    public int findLUSlength(String[] strs) {
        Arrays.sort(strs, new Comparator<String>() {//按照长度从大到小排序
            @Override
            public int compare(String o1, String o2) {
                return o2.length() - o1.length();
            }
        });
        for (int i = 0;i < strs.length;i ++){
            int noMatches = strs.length - 1;
            for (int j = 0;j < strs.length;j ++){
                if (i != j && isSub(strs[i],strs[j])){
                    noMatches --;
                }
                if (noMatches == 0){
                    return strs[i].length();
                }
            }
        }
        return -1;
    }
    public boolean isSub(String s1,String s2){
        int i = 0;
        for (char c : s2.toCharArray()){
            if (i < s1.length() && s1.charAt(i) == c){
                i ++;
            }
        }
        if (i == s1.length()){
            return false;
        }
        return true;
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!