[LeetCode] 884. 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:
0 <= A.length <= 200
0 <= B.length <= 200
A
andB
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/
[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)
最新文章
- [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法
- 文件处理命令:awk
- tkprof
- Android系统下检测Wifi连接互联网是否正常的代码
- oracle 事务处理 注意事项(笔记)
- HD2043猜密码
- php-工厂模式(转)
- [Android][Android Studio] *.jar 与 *.aar 的生成与*.aar导入项目方法
- bnu 4352 XsugarX的疯狂按键识别(暴力模拟)
- linux术语解析(持续更新)
- windows7 64位下运行 regsvr32 注册ocx或者dll的方法
- onethink和phpwind共享
- [ACM] hdu 1671 Phone List (特里)
- python中关于元组的操作
- swift 录制多个音频 并将音频转换为mp3 并合成多个mp3文件为一个文件
- 【机器学习】正则化的线性回归 —— 岭回归与Lasso回归
- iOS开发之Swift 4 JSON 解析指南
- Linux中 ./configure --prefix命令
- List of numerical libraries,Top Numerical Libraries For C#
- 01-Python的基础知识2
热门文章
- poj-2234 Matches Game Nim
- 区分 JVM 内存结构、 Java 内存模型 以及 Java 对象模型 三个概念
- WinForm 程序在系统托盘显示
- 基于OceanStor Dorado V3存储之精简高效 Smart 系列特性
- Pandas 学习 第9篇:DataFrame - 数据的输入输出
- mysql参数之innodb_buffer_pool_size大小设置
- python随机选取目录下的若干个文件
- PIE调用Python获得彩色直方图
- vue中使用axios进行ajax请求数据(跨域配置)
- 【设计模式】Builder