LC522-最长特殊序列 II

168 阅读1分钟

题目名称:最长特殊序列 II

给定字符串列表 strs ,返回其中 最长的特殊序列 的长度。如果最长特殊序列不存在,返回 -1 。

特殊序列 定义如下:该序列为某字符串 独有的子序列(即不能是其他字符串的子序列)

 s 的 子序列可以通过删去字符串 s 中的某些字符实现。

  • 例如,"abc" 是 "aebdc" 的子序列,因为您可以删除"aebdc"中的下划线字符来得到 "abc" 。"aebdc"的子序列还包括"aebdc"、 "aeb" 和 "" (空字符串)。

示例 1:

输入: strs = ["aba","cdc","eae"]
输出: 3

示例 2:

输入: strs = ["aaa","aaa","aa"]
输出: -1

提示:

  • 2 <= strs.length <= 50
  • 1 <= strs[i].length <= 10
  • strs[i] 只包含小写英文字母

思路分析

假设所有字串长度都是相等的,那么答案要么是len要么是-1. 当存在唯一字串的时候,答案为len,所有字串都不唯一,答案为-1. 假如对于最长的字串,无法找到答案。那么对于短一些的字串,要想得到答案,首先同理它也必须是唯一的,其次更长的字串中不应包含它。

基本思想其实也是暴力求解所有的可能性,利用回溯得到每一个字符串的组合结果,其中包括删除某些字母得到的组合结果。

从所有可能的结果出发,利用Hash表得到非重复subString(也就是公共子串)的存在情况,同时比较赋值全局的最大非重复子串长度, 得到最后的结果。

  • A是B的子序列,那么A的所有子序列也是B的子序列,所以A和A的子序列都不能为答案
  • A不是B的子序列,A的子序列可能是B的子序列也可能不是,但是无论子序列是不是B的子序列长度都小于A,所以A即为答案

综上可得只需要判断A是不是另一个B的子序列即可得到A是否为一个合法的答案,取所有轮中最大的答案即可

Code实现

public int findLUSlength(String[] strs) {
    // sort
    Arrays.sort(strs, (o1, o2) -> (o2.length() - o1.length()));

    // find unique
    Map < String, Integer > strCnt = new HashMap < > ();
    for (String str: strs) {
        strCnt.put(str, strCnt.getOrDefault(str, 0) + 1);
    }

    // check unique
    for (String str: strs) {
        if (strCnt.get(str) == 1) {
            if (check(strs, str)) {
                return str.length();
            }
        }
    }
    return -1;
}

private boolean check(String[] strs, String tar) {

    int n = tar.length();
    for (String str: strs) {
        int len = str.length();
        // check all longer str
        if (len <= n) {
            break;
        }
        int curT = 0;
        int curS = 0;
        while (true) {
            // contain
            if (curT == n) {
                return false;
            }
            // not contain
            if (curS == len) {
                break;
            }
            if (tar.charAt(curT) == str.charAt(curS)) {
                curT++;
                curS++;
            } else {
                curS++;
            }
        }
    }

    return true;
}

结果

Snipaste_2023-04-25_21-39-58.png

算法复杂度分析

  • 时间复杂度:O(n)O(n)
  • 空间复杂度:O(1)O(1)