Wednesday, August 5, 2020

884. Uncommon Words from Two Sentences

Q:

We are given two sentences A and B.  (A sentence is a string of space separated words.  Each word consists only of lowercase letters.)

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Return a list of all uncommon words. 

You may return the list in any order.

 

    Example 1:

    Input: A = "this apple is sweet", B = "this apple is sour"
    Output: ["sweet","sour"]
    

    Example 2:

    Input: A = "apple apple", B = "banana"
    Output: ["banana"]
    

     

    Note:

    1. 0 <= A.length <= 200
    2. 0 <= B.length <= 200
    3. A and B both contain only spaces and lowercase letters.

    A:

    class Solution {
    public:
        vector<string> uncommonFromSentences(string A, string B) {
            istringstream iss(A);
            vector<string> strA(istream_iterator<string>{iss},istream_iterator<string>());
            istringstream iss2(B);
            vector<string> strB(istream_iterator<string>{iss2},istream_iterator<string>());
            
            unordered_map<string, int > S1;
            for(auto & s : strA){
                S1[s] +=1;
            }
            unordered_map<string, int > S2;
            for(auto & s : strB){
                S2[s] +=1;
            }
            vector<string> res;
            for(auto & s : strA){
                if(S1[s] == 1 && S2.find(s)==S2.end())
                {
                    res.push_back(s);
                    // cout << s << endl;
                }
            }
            for(auto & s : strB)
                if(S2[s] == 1 && S1.find(s)==S1.end())
                    res.push_back(s);
            
            return res;
        }
    };


    一开始题意没有看清楚,  if it appears exactly once in one of the sentences

    Learned:    how to split string via space in C++
            istringstream iss(A);
            vector<string> strA(istream_iterator<string>{iss},istream_iterator<string>());

    No comments:

    Post a Comment