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.

这道题给了我们两个字符串,表示两个句子,每个句子中都有若干个单词,用空格隔开,现在让我们找出两个句子中唯一的单词。那么只要把每个单词都提取出来,然后统计其在两个句子中出现的个数,若最终若某个单词的统计数为1,则其一定是符合题意的。所以我们可以先将两个字符串拼接起来,中间用一个空格符隔开,这样提取单词就更方便一些。在 Java 中,可以使用 split() 函数来快速分隔单词,但是在 C++ 中就没这么好命,只能使用字符串流 istringstream,并用一个 while 循环来一个一个提取。当建立好了单词和其出现次数的映射之后,再遍历一遍 HashMap,将映射值为1的单词存入结果 res 即可,参见代码如下:

class Solution {
public:
vector<string> uncommonFromSentences(string A, string B) {
vector<string> res;
unordered_map<string, int> wordCnt;
istringstream iss(A + " " + B);
while (iss >> A) ++wordCnt[A];
for (auto a : wordCnt) {
if (a.second == 1) res.push_back(a.first);
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/884

参考资料:

https://leetcode.com/problems/uncommon-words-from-two-sentences/

https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/158967/C%2B%2BJavaPython-Easy-Solution-with-Explanation

https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/158981/Java-3-liner-and-5-liner-using-HashMap-and-HashSets-respectively.

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

最新文章

  1. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法
  2. 文件处理命令:awk
  3. tkprof
  4. Android系统下检测Wifi连接互联网是否正常的代码
  5. oracle 事务处理 注意事项(笔记)
  6. HD2043猜密码
  7. php-工厂模式(转)
  8. [Android][Android Studio] *.jar 与 *.aar 的生成与*.aar导入项目方法
  9. bnu 4352 XsugarX的疯狂按键识别(暴力模拟)
  10. linux术语解析(持续更新)
  11. windows7 64位下运行 regsvr32 注册ocx或者dll的方法
  12. onethink和phpwind共享
  13. [ACM] hdu 1671 Phone List (特里)
  14. python中关于元组的操作
  15. swift 录制多个音频 并将音频转换为mp3 并合成多个mp3文件为一个文件
  16. 【机器学习】正则化的线性回归 —— 岭回归与Lasso回归
  17. iOS开发之Swift 4 JSON 解析指南
  18. Linux中 ./configure --prefix命令
  19. List of numerical libraries,Top Numerical Libraries For C#
  20. 01-Python的基础知识2

热门文章

  1. poj-2234 Matches Game Nim
  2. 区分 JVM 内存结构、 Java 内存模型 以及 Java 对象模型 三个概念
  3. WinForm 程序在系统托盘显示
  4. 基于OceanStor Dorado V3存储之精简高效 Smart 系列特性
  5. Pandas 学习 第9篇:DataFrame - 数据的输入输出
  6. mysql参数之innodb_buffer_pool_size大小设置
  7. python随机选取目录下的若干个文件
  8. PIE调用Python获得彩色直方图
  9. vue中使用axios进行ajax请求数据(跨域配置)
  10. 【设计模式】Builder