Categories:

Tags:



Problem

A sentence is a string of single-space separated words where 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.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.

Constraints

  • 1 <= s1.length, s2.length <= 200
  • s1 and s2 consist of lowercase English letters and spaces.
  • s1 and s2 do not have leading or trailing spaces.
  • All the words in s1 and s2 are separated by a single space.

Solution

The problem Uncommon Words from Two Sentences can be solved by counting the number of words in both sentences and finding ones that appear only once.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  private:
    unordered_map<string, int> hashmap;

  public:
    void countWords(string str)
    {
        string word;

        str += ' ';
        for (char &ch : str)
        {
            if (ch != ' ')
                word += ch;
            else
            {
                hashmap[word] += 1;
                word = "";
            }
        }
    }

    vector<string> uncommonFromSentences(string s1, string s2)
    {
        countWords(s1);
        countWords(s2);

        vector<string> ret;
        for (auto &[key, val] : hashmap)
            if (val == 1)
                ret.push_back(key);

        return ret;
    }
};