classSolution: defstringMatching(self, words: List[str]) -> List[str]: ans = [] for i, x inenumerate(words): for j, y inenumerate(words): if j != i and x in y: ans.append(x) break return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: vector<string> stringMatching(vector<string>& words){ vector<string> ret; for (int i = 0; i < words.size(); i++) { for (int j = 0; j < words.size(); j++) { if (i != j && words[j].find(words[i]) != string::npos) { ret.push_back(words[i]); break; } } } return ret; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { public List<String> stringMatching(String[] words) { List<String> ret = newArrayList<String>(); for (inti=0; i < words.length; i++) { for (intj=0; j < words.length; j++) { if (i != j && words[j].contains(words[i])) { ret.add(words[i]); break; } } } return ret; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution { public IList<string> StringMatching(string[] words) { IList<string> ret = new List<string>(); for (int i = 0; i < words.Length; i++) { for (int j = 0; j < words.Length; j++) { if (i != j && words[j].Contains(words[i])) { ret.Add(words[i]); break; } } } return ret; } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
char ** stringMatching(char ** words, int wordsSize, int* returnSize){ char **ret = (char **)malloc(sizeof(char *) * wordsSize); int pos = 0; for (int i = 0; i < wordsSize; i++) { for (int j = 0; j < wordsSize; j++) { if (i != j && strstr(words[j], words[i])) { ret[pos++] = words[i]; break; } } } *returnSize = pos; return ret; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var stringMatching = function(words) { const ret = []; for (let i = 0; i < words.length; i++) { for (let j = 0; j < words.length; j++) { if (i !== j && words[j].search(words[i]) !== -1) { ret.push(words[i]); break; } } } return ret; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11
funcstringMatching(words []string) (ans []string) { for i, x := range words { for j, y := range words { if j != i && strings.Contains(y, x) { ans = append(ans, x) break } } } return }
复杂度分析
时间复杂度:O(n^2 \times L^2),其中 n 是字符串数组的长度,L 是字符串数组中最长字符串的长度。使用 KMP 字符串匹配算法可以将时间复杂度优化到 O(n^2 \times T),其中 T 是字符串数组中所有字符串的平均长度。