String Matching in an Array
💻 coding

String Matching in an Array

1 min read 291 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to find all strings in an array that are substrings of other strings.
  • 2Examples illustrate that 'as' is a substring of 'mass' and 'hero' is a substring of 'superhero'.
  • 3The solution involves a nested loop to compare each string, resulting in O(n^2) time complexity.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to find all strings in an array that are substrings of other strings."

— String Matching in an Array

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

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

Example 1:

Input: words = ["mass","as","hero","superhero"]

Output: ["as","hero"]

Explanation: "as" is a substring of "mass" and "hero" is a 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.

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 class StringMatchingArray
 {
 public void execute()
 {
 string[] words = new string[] { "mass", "as", "hero", "superhero" };

 var res = StringMatching(words);
 }

 public IList<string> StringMatching(string[] words)
 {
 //to Store unique solution.
 var ListStr = new HashSet<string>();
 for (int i = 0; i < words.Length-1; i++)
 {
 for(int j = i+1; j < words.Length; j++)
 {
 string subStr;
 if (words[i].Length>words[j].Length)
 subStr = ReturnSubstring(words[i], words[j]);
 else
 subStr = ReturnSubstring(words[j], words[i]);
 if (subStr != null)
 ListStr.Add(subStr);
 }
 }

 var result = new List<string>();
 foreach (var item in ListStr)
 {
 result.Add(item);
 }
 return result;
 }

 private string ReturnSubstring(string word1, string word2)
 {
 for (int i = 0; i < word1.Length-word2.Length+1; i++)
 {
 for (int j = 0; j < word2.Length; j++)
 {
 if (word1[i + j] != word2[j])
 break;
 if (j == word2.Length - 1)
 {
 return word2;
 }
 }
 }
 return null;
 }
 }
}

Time Complexity: O(n^2) for comparing character by character

Space Complexity: O(n) for storing in Linked list and returning in result

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 3 May 2020 · 1 min read · 291 words

Part of AskGif Blog · coding

You might also like

String Matching in an Array | AskGif Blog