zoukankan      html  css  js  c++  java
  • 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 };
  • 相关阅读:
    java exception
    【洛谷P1627】 【CQOI2009】中位数
    切蛋糕
    【NOIP2015Day2T2】【洛谷P2679】子串
    【NOIP2017Day1T3】【洛谷P3953】逛公园
    【bzoj1082】【SCOI2005】栅栏
    搬砖
    花花的森林
    跳跳棋
    异或
  • 原文地址:https://www.cnblogs.com/gsz-/p/9463306.html
Copyright © 2011-2022 走看看