# 數組Leetcode解決方案中的字符串匹配

`words = ["mass","as","hero","superhero"]`
`["as","hero"]`

`words = ["leetcode","et","code"]`
`["et","code"]`

## 數組Leetcode解決方案中用於字符串匹配的代碼

### C ++代碼

```#include <bits/stdc++.h>
using namespace std;

bool isSubstr(string a, string b){
int n = a.size(), m = b.size();
for(int i=0;i<=n-m;i++){
if(a.substr(i, m) == b)
return true;
}
return false;
}

vector<string> stringMatching(vector<string>& words) {
unordered_set<string> tmp;
int n = words.size();
for(int i=0;i<n-1;i++){
string curWord = words[i];
for(int j=i+1;j<n;j++){
string nextWord = words[j];
if(isSubstr(curWord, nextWord))
tmp.insert(nextWord);
if(isSubstr(nextWord, curWord))
tmp.insert(curWord);
}
}
return vector<string>(tmp.begin(), tmp.end());
}

int main(){
vector<string> input({"mass","as","hero","superhero"});
vector<string> v = stringMatching(input);
for(auto x: v)
cout<<x<<" ";
}
```
`hero as`

### Java代碼

```import java.util.*;
import java.lang.*;
import java.io.*;

class Main
{
public static List<String> stringMatching(String[] words) {
HashSet<String> tmp = new HashSet<>();

int n = words.length;
for(int i = 0; i<n-1; i++) {
String curWord = words[i];
for(int j = i+1; j<n; j++) {
String nextWord = words[j];
if(curWord.contains(nextWord))
if(nextWord.contains(curWord))
}
}

return new ArrayList<String>(tmp);
}

public static void main (String[] args) throws java.lang.Exception{
String[] words = {"mass","as","hero","superhero"};
List<String> list = stringMatching(words);
for(String x: list)
System.out.print(x+" ");
}
}```
`hero as`

## 複雜度分析

### 時間複雜度

O（N ^ 2 * | S |）， 因為我們使用了兩個嵌套循環，它們取決於輸入字符串的數量。 然後該函數用於查找字符串是否為其他需要的子字符串 O（| S |） 時間。