[translate by ChatGPT] Here we need to check pairs to find how many strings are substrings of others, so I compared them pairwise. However, I noticed that some people first sort the strings by length, so they only need to compare in one direction.

Code

class Solution {
public:
    vector<string> stringMatching(vector<string>& words) {
        const int n = words.size();
        unordered_set<int> ansIdx;
        for(int i = 0 ; i < n ; ++i) {
            for(int j = i+1 ; j < n ; ++j) {
                string& s1 = words[i];
                string& s2 = words[j];
                if (isSubString(s2, s1)) ansIdx.insert(i);
                if (isSubString(s1, s2)) ansIdx.insert(j);
            }
        }
        vector<string> ans;
        for(int i = 0 ; i < n ; ++i) {
            if (ansIdx.find(i) !=  ansIdx.end()) {
                ans.push_back(words[i]);
            }
        }
        return ans;
        
    }
    bool isSubString(string s1, string s2) {
        return s1.find(s2) != string::npos;
    }
};