884. Uncommon Words from Two Sentences

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
分别找出和两个字符串中各在一个中出现一次而在另一个没有出现的单词。

2,题目思路
对于这道题,目的是找到在一个字符串中仅仅出现一次,而在另一个字符串中没有出现的单词。因此,这里涉及到了不同单词的数量统计问题。而对于这样的问题,一般都会使用一个hashMap来进行实现。也就是unordered_map来辅助实现。
在一个字符串出现一次,在另一个没出现,其实就是说,对于两个字符串所组成的整个字符串而言,只要出现了一次的单词,就一定是满足条件的单词了。
于是,我们就可以对这个长字符串进行遍历,然后找到其中仅仅出现一次的单词,最后返回即可。

3,程序源码

class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) {
        unordered_map<string, int> cnt;
        vector<string> res;
        string total = A + " " + B, tmp = "";
        istringstream in(total);
        while(in>>tmp)
            cnt[tmp]++;
        for(auto c : cnt)
        {
            if(c.second == 1)   res.push_back(c.first);
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值