Leetcode 884: Uncommon Words from Two Sentences

问题描述:
We are given two sentences s1 and s2. (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.
找出s1中只出现一次且在s2中未出现过的单词,反之亦然

思路:
这道题的英文表达有点误导人,不是uncommon word 而是 unique word
这样我们把两个字符串合并(用空格隔开),再用一个哈希表记录单词以及出现的次数。
我的方法有点绕,用了两个哈希表,两个数组

代码如下:

class Solution {
    Map<String,Integer> map1=new HashMap<>();
    Map<String,Integer> map2=new HashMap<>();
    
    public String[] uncommonFromSentences(String s1, String s2) {
        s1=s1+" ";
        s2=s2+" ";
        addWordsToMap(s1, map1);
        addWordsToMap(s2, map2);
        List<String> list=new ArrayList<>();
        for(String a: map1.keySet()){
            if((map1.get(a)==1)&&(!map2.containsKey(a))){
                list.add(a);
            }
        }
        for(String a: map2.keySet()){
            if((map2.get(a)==1)&&(!map1.containsKey(a))){
                list.add(a);
            }
        }
        String[] ans=new String[list.size()];
        for(int i=0; i<list.size(); i++){
            ans[i]=list.get(i);
        }
        return ans;
    }
    
    private void addWordsToMap(String s, Map x){
        int slower=0;
        for(int faster=1; faster<s.length(); faster++){
            if((s.charAt(faster)==' ')&&(s.charAt(faster-1)!=' ')){
                String nextWord=s.substring(slower,faster);
                if(!x.containsKey(nextWord)){
                    x.put(nextWord,1);
                }
                else{
                    x.put(nextWord,2);
                }
            }
            if((s.charAt(faster)!=' ')&&(s.charAt(faster-1)==' ')){
                slower=faster;
            }
        }
    }
}

时间复杂度: O(m+n)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值