LeetCode 884. 两句话中的不常见单词(C++、python)

给定两个句子 A 和 B 。 (句子是一串由空格分隔的单词。每个单词仅由小写字母组成。)

如果一个单词在其中一个句子中只出现一次,在另一个句子中却没有出现,那么这个单词就是不常见的

返回所有不常用单词的列表。

您可以按任何顺序返回列表。

 

示例 1:

输入:A = "this apple is sweet", B = "this apple is sour"
输出:["sweet","sour"]

示例 2:

输入:A = "apple apple", B = "banana"
输出:["banana"]

 

提示:

0 <= A.length <= 200

0 <= B.length <= 200

A 和 B 都只包含空格和小写字母。

C++

class Solution {
public:
    vector<string> uncommonFromSentences(string A, string B) 
    {
        unordered_map<string,int> tmp;
        int m=A.length();
        int n=B.length();
        vector<int> idx1;
        vector<int> idx2;
        vector<string> res;
        for(int i=0;i<m;i++)
        {
            if(A[i]==' ')
            {
                idx1.push_back(i);
            }
        }
        for(int i=0;i<n;i++)
        {
            if(B[i]==' ')
            {
                idx2.push_back(i);
            }
        }
        int mm=idx1.size();
        int nn=idx2.size();
        if(0==mm)
        {
            tmp[A]++;
        }
        else
        {
            tmp[A.substr(0,idx1[0])]++;
            tmp[A.substr(idx1[mm-1]+1,-1)]++;            
            for(int i=0;i<mm-1;i++)
            {
                tmp[A.substr(idx1[i]+1,idx1[i+1]-idx1[i]-1)]++;
            }
        }
        if(0==nn)
        {
            tmp[B]++;
        }
        else
        {
            tmp[B.substr(0,idx2[0])]++;
            tmp[B.substr(idx2[nn-1]+1,-1)]++;
            for(int i=0;i<nn-1;i++)
            {
                tmp[B.substr(idx2[i]+1,idx2[i+1]-idx2[i]-1)]++;
            }
        }
        for(auto item:tmp)
        {
            if(item.second==1)
            {
                res.push_back(item.first);
            }
        }
        return res;        
    }
};

python

class Solution:
    def uncommonFromSentences(self, A, B):
        """
        :type A: str
        :type B: str
        :rtype: List[str]
        """
        res=[]
        a=A.split(' ')
        b=B.split(' ')
        dic1={}
        dic2={}
        for i in range(len(a)):
            if a[i] not in dic1:
                dic1[a[i]]=1
            else:
                dic1[a[i]]+=1
        for i in range(len(b)):
            if b[i] not in dic2:
                dic2[b[i]]=1
            else:
                dic2[b[i]]+=1
        for key in dic1:
            if dic1[key]==1 and key not in dic2:
                res.append(key)
        for key in dic2:
            if dic2[key]==1 and key not in dic1:
                res.append(key)
        return res

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值