LC1408-数组中的字符串匹配

80 阅读1分钟

题目名称:数组中的字符串匹配

给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。

如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 words[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。

 

示例 1:

输入: words = ["mass","as","hero","superhero"]
输出: ["as","hero"]
解释: "as""mass" 的子字符串,"hero""superhero" 的子字符串。
["hero","as"] 也是有效的答案。

示例 2:

输入: words = ["leetcode","et","code"]
输出: ["et","code"]
解释: "et""code" 都是 "leetcode" 的子字符串。

示例 3:

输入: words = ["blue","green","bu"]
输出: []

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] 仅包含小写英文字母。
  • 题目数据 保证 每个 words[i] 都是独一无二的。

思路分析

1.先获得最大长度的字符串,再判断比此字符串的长度小的字符串是否是此字符串的子字符串。 2.while(true)循环判断。 3.因为需要循环判断,因此设一个boolean[]来作为结束循环的依据。 4.boolean[]还可以用来将第1步中的“比此字符串的长度小的字符串”与“此字符串”设为true

将字符串从长到短排序 将最短的字符串words[s-1]作为模式串 从第一个字符串作为目标串开始,向后遍历 如果找到了匹配的目标串,则终止遍历,并将模式串压入结果数组 如果目标串与模式串长度相同,终止遍历 弹出数组最后一个元素,即移除已确定的模式串 重复2,直到数组为空

Code实现

public List < String > stringMatching(String[] words) {
    List < String > wordList = new ArrayList < > ();
    Collections.addAll(wordList, words);
    Collections.sort(wordList, (o1, o2) - > o2.length() - o1.length());

    List < String > res = new ArrayList < > ();
    while (wordList.size() != 0) {
        int cmpIdx = wordList.size() - 1;
        for (int i = 0; i < wordList.size() - 1; i++) {
            if (wordList.get(i).length() == wordList.get(cmpIdx).length()) break;
            if (wordList.get(i).contains(wordList.get(cmpIdx))) {
                res.add(wordList.get(cmpIdx));
                break;
            }
        }
        wordList.remove(wordList.size() - 1);
    }
    return res;
}

结果

Snipaste_2023-05-04_23-37-53.png

算法复杂度分析

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