Skip to content

Commit eb928f8

Browse files
committed
added String Matching in an Array (easy)
1 parent 2ab4913 commit eb928f8

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
# String Matching in an Array
3+
[Leetcode Link](https://leetcode.com/problems/string-matching-in-an-array/)
4+
5+
## Problem:
6+
7+
Given an array of string words. Return all strings in words which is substring of another word in **any** order.
8+
9+
String `words[i]` is substring of `words[j]`, if can be obtained removing some characters to left and/or right side of `words[j]`.
10+
11+
## Example:
12+
13+
```
14+
Input: words = ["mass","as","hero","superhero"]
15+
Output: ["as","hero"]
16+
Explanation: "as" is substring of "mass" and "hero" is substring of "superhero".
17+
["hero","as"] is also a valid answer.
18+
```
19+
```
20+
Input: words = ["leetcode","et","code"]
21+
Output: ["et","code"]
22+
Explanation: "et", "code" are substring of "leetcode".
23+
```
24+
```
25+
Input: words = ["blue","green","bu"]
26+
Output: []
27+
```
28+
29+
## Note:
30+
31+
- `1 <= words.length <= 100`
32+
- `1 <= words[i].length <= 30`
33+
- `words[i]` contains only lowercase English letters.
34+
- It's guaranteed that `words[i]` will be unique.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
from typing import List
2+
3+
def stringMatching(words: List[str]) -> List[str]:
4+
substrings = list()
5+
words.sort(key=lambda w: len(w))
6+
for i in range(len(words)):
7+
for j in range(i+1, len(words)):
8+
# if words[i] is substring of words[j], insert to substring and exit current loop
9+
if words[i] in words[j]:
10+
substrings.append(words[i])
11+
break
12+
return substrings
13+
14+
15+
16+
# test driver
17+
words = ["mass","as","hero","superhero"]
18+
print("Input: words =", words)
19+
print("Output:", stringMatching(words))
20+
print()
21+
22+
words = ["leetcode","et","code"]
23+
print("Input: words =", words)
24+
print("Output:", stringMatching(words))
25+
print()
26+
27+
words = ["blue","green","bu"]
28+
print("Input: words =", words)
29+
print("Output:", stringMatching(words))
30+
print()

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ Languages used: Java and Python
2020
- [Maximize Distance to Closest Person](Easy/MaximizeDistanceToClosestPerson)
2121
- [Find Common Characters](Easy/FindCommonCharacters)
2222
- [Third Maximum Number](Easy/ThirdMaximumNumber)
23+
- [String Matching in an Array](Easy/StringMatchingInArray)
2324
- Medium
2425
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
2526
- [Distribute Coins in Binary Tree](Medium/DistributionCoinsInBinaryTree)

0 commit comments

Comments
 (0)