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.

这题直接两两的进行比较就行了,但是可以像冒泡算法一样去减少一部分遍历,同时需要注意结果集可能会有相同的,所以可以用set来去重。


class StringMatchingInAnArray : public Solution {
public:
    void Exec() {

    }
    vector<string> stringMatching(vector<string>& words) {
        set<string> res;
        for (int i = 0; i < words.size(); i++) {
            for (int j = i + 1; j < words.size(); j++) {
                size_t pos = std::string::npos;
                if (words[i].size() == words[j].size()) {
                    continue;
                }
                if (words[i].size() > words[j].size()) {
                    pos = words[i].find(words[j]);
                } else {
                    pos = words[j].find(words[i]);
                }
                if (pos != std::string::npos) {
                    res.insert(words[i].size() < words[j].size() ? words[i] : words[j]);
                }
            }
        }
        return vector<string>(res.begin(), res.end());
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day