888. Uncommon Words from Two Sentences

题目描述:

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.

解题思路:

使用unordered_map<string,int>记录每个单词出现的次数,次数为一的单词加入返回的vector。

代码:

 1 class Solution {
 2 public:
 3     vector<string> uncommonFromSentences(string A, string B) {
 4         istringstream sin1(A);
 5         istringstream sin2(B);
 6         string word;
 7         unordered_map<string, int> words;
 8         vector<string> res;
 9         while (sin1>>word) {
10             words[word]++;
11         }
12         while (sin2>>word) {
13             words[word]++;
14         }
15         for (auto iter = words.begin(); iter != words.end(); ++iter) {
16             if (iter->second == 1) {
17                 res.push_back(iter->first);
18             }
19         }
20         return res;
21     }
22 };

 

posted @ 2018-08-12 16:09  gszzsg  阅读(124)  评论(0编辑  收藏  举报