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

问题:ide

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

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

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

Example 1:排序

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

Note:element

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

解决:rem

①  暴力解决。遍历全部的字符串,对于每一个遍历到的字符串,再和全部的其余的字符串比较,看是否是某一个字符串的子序列,若是都不是的话,那么当前字符串就是一个非共同子序列,用其长度来更新结果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();
    }
}get

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

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;     } }

相关文章
相关标签/搜索