1408. 数组中的字符串匹配

题目:给你一个字符串数组 words ,数组中的每个字符串都可以看作是一个单词。请你按 任意 顺序返回 words 中是其他单词的子字符串的所有单词。

如果你可以删除 words[j] 最左侧和/或最右侧的若干字符得到 word[i] ,那么字符串 words[i] 就是 words[j] 的一个子字符串。

示例 1:

输入:words = ["mass","as","hero","superhero"]
输出:["as","hero"]
解释:"as" 是 "mass" 的子字符串,"hero" 是 "superhero" 的子字符串。
["hero","as"] 也是有效的答案。
示例 2:

输入:words = ["leetcode","et","code"]
输出:["et","code"]
解释:"et" 和 "code" 都是 "leetcode" 的子字符串。

1.原创

class Solution {
public:
    bool substring(string Str1,string Str2){//判断子串
     if((Str2.find(Str1,0))!=string::npos)
        return true;
    else
        return false;
    }
    vector<string> stringMatching(vector<string>& words) {
        vector<string> res;
        //这里是lamdba的写法,实际上把它写成一个函数
        sort(words.begin(),words.end(),[](string a, string b ) {return a.size() < b.size();});
        //cout<<words[0];
        for (int i=0;i<words.size()-1;++i){
            for (int j=i+1;j<words.size();++j){
                if (substring(words[i],words[j])){
                    res.push_back(words[i]);
                    break; //结束内层循环
                }
            }
        }
        return res;
    }
};

2.题解

class Solution {
public:
    vector<string> stringMatching(vector<string>& words) {
        sort(words.begin(), words.end(), [](const string& a, const string& b) {
            return a.size() > b.size();
        });
        vector<string> ret;
        string tmp = words[0];
        for (int i = 1; i < words.size(); ++i) {
            if (tmp.find(words[i]) != string::npos) {
                ret.push_back(words[i]);
            }
            tmp += "#" + words[i]; //需要使用分隔符
        }
        return ret;
    }
};

作者:xiao-fu-zi-1
链接:https://leetcode-cn.com/problems/string-matching-in-an-array/solution/c-bao-li-wo-ye-yao-ban-fa-ma-by-xiao-fu-zi-1/
原文地址:https://www.cnblogs.com/USTC-ZCC/p/14479026.html