跳转至

1408.String Matching in an Array

Tags: Easy String

Links: https://leetcode.com/problems/string-matching-in-an-array/


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

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

Example 1:

Input: words = ["mass","as","hero","superhero"]
Output: ["as","hero"]
Explanation: "as" is substring of "mass" and "hero" is 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.

class Solution {
public:
    vector<string> stringMatching(vector<string>& words) {
        std::ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);

        int n = words.size();
        sort(words.begin(), words.end(), 
            [](const string & s1, const string & s2){ return s1.size() < s2.size();});

        vector<string> res;
        for (int i = 0; i < n - 1; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (words[j].find(words[i]) != string::npos) {
                    res.push_back(words[i]); break;
                }
            }
        }

        return res;
    }
};

显然长的字符串不可能是短的字符串的子串,那么可以先按字符串的长短进行排序,发现n = 100,那么暴力O(n^2)肯定可以通过。