LeetCode | 1408. String Matching in an Array數組中的字符串匹配【Python】

LeetCode 1408. String Matching in an Array數組中的字符串匹配【Easy】【Python】【字符串】

Problem

LeetCode

Given an array of string words. Return all strings in words which is substring of another word in any order.

String words[i] is substring of words[j], if can be obtained removing some characters to left and/or right side of words[j].

Example 1:

Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
["hero","as"] is also a valid answer.

Example 2:

Input: words = ["leetcode","et","code"]
Output: ["et","code"]
Explanation: "et", "code" are substring of "leetcode".

Example 3:

Input: words = ["blue","green","bu"]
Output: []

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 30
  • words[i] contains only lowercase English letters.
  • It’s guaranteed that words[i] will be unique.

問題

力扣

給你一個字符串數組 words ,數組中的每個字符串都可以看作是一個單詞。請你按 任意 順序返回 words 中是其他單詞的子字符串的所有單詞。

如果你可以刪除 words[j] 最左側和/或最右側的若干字符得到 word[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] 都是獨一無二的。

思路

字符串

暴力,最後要去重。

時間複雜度: O(n^2)
空間複雜度: O(n)

Python3代碼
from typing import List
import copy

class Solution:
    def stringMatching(self, words: List[str]) -> List[str]:
        n = len(words)
        res = []
        for i in range(n):
            temp = copy.deepcopy(words)
            temp.remove(words[i])

            for j in range(n - 1):
                if words[i] in temp[j]:
                    res.append(words[i])
        return list(set(res))

GitHub鏈接

Python

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章