Solution using stringstream and set


#1
vector<int> Solution::solve(string A, vector<string> &B) {
set<string> st;

for(int i = 0;i<A.length();i++)
{
    if(A[i]=='_')
    A[i] = ' ';
}

stringstream ss(A);
while(!ss.eof())
{
    string s;
    ss>>s;
    //cout<<s<<" ";
    st.insert(s);
} 


map<int,vector<int>,greater<int>> m;
int i = 0;
for(string str : B)
{
    int count = 0;
    for(int i = 0;i<str.length();i++)
    {
        if(str[i]=='_')
        str[i] = ' ';
    }
    stringstream ss(str);
    while(!ss.eof())
    {
        string s;
        ss>>s;
        if(st.find(s)!=st.end())
        {
            count++;
        }
    } 
    m[count].push_back(i);
    i++;
}

vector<int> res;

for(auto it : m)
{
    vector<int> temp = it.second;
    for(int i : temp)
    res.push_back(i);
}

return res;

}


#2

Concise C++ code, Same approach as above, using Map and Set

vector<int> Solution::solve(string A, vector<string> &B) {
    unordered_set<string>st;
    string temp = "";
    int n=A.size();
    for(int i=0; i<=n; i++) {
        if(i<n && A[i]!= '_') {
            temp+=A[i];
        } else  {
            st.insert(temp);
            temp = "";
        }
    }
    map<int, vector<int>, greater<int>>M;
    for(int i=0; i<B.size(); i++) {
        string s = B[i];
        temp = "";
        int count = 0, sz = s.size();
        for(int j=0; j<=sz; j++) {
            if(j<sz && s[j] != '_') {
                temp += s[j];
            } else {
                if(st.find(temp) != st.end()) {
                    count++;
                }
                temp = "";
            }
        }
        M[count].push_back(i);
    }
    vector<int>res;
    for(auto it = M.begin(); it!= M.end(); it++) {
        res.insert(res.end(), it->second.begin(), it->second.end());
    }
    return res;
}