当前位置: 代码迷 >> 综合 >> Leetcode 1408. String Matching in an Array
  详细解决方案

Leetcode 1408. String Matching in an Array

热度:46   发布时间:2023-12-12 21:09:21.0

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

String Matching in an Array

2. Solution

  • Version 1
class Solution:def stringMatching(self, words: List[str]) -> List[str]:result = set()length = len(words)flags = [0 for i in range(length)]for i in range(length):if flags[i]:continuefor j in range(i+1, length):if flags[j]:continueif len(words[i]) < len(words[j]):if words[i] in words[j]:flags[i] = 1result.add(words[i])else:if words[j] in words[i]:flags[j] = 1result.add(words[j])return result
  • Version 2
class Solution:def stringMatching(self, words: List[str]) -> List[str]:words.sort(key=len) result = set()length = len(words)for i in range(length):for j in range(i+1, length):if words[i] in words[j]:result.add(words[i])breakreturn result

Reference

  1. https://leetcode.com/problems/string-matching-in-an-array/
  相关解决方案