leetcode讲解--884. Uncommon Words from Two Sentences

本文介绍了一种使用HashMap来找出两个句子中不常见单词的方法。通过遍历每个句子并将单词计数存入HashMap,可以有效地找出那些只在一个句子中出现一次的单词。最后,将这些单词收集到一个列表中并返回。

题目

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.

题目地址

讲解

用hashmap记录每一个单词

Java代码

class Solution {
    private Map<String, Integer> map = new HashMap<>();
    public String[] uncommonFromSentences(String A, String B) {
        List<String> result = new ArrayList<>();
        countString(A);
        countString(B);
        for(String key:map.keySet()){
            if(map.get(key)==1){
                result.add(key);
            }
        }
        String[] str = new String[result.size()];
        return result.toArray(str);
    }
    
    private void countString(String A){
        int index=0;
        for(int i=0;i<A.length();i++){
            if(A.charAt(i)==' '){
                Integer count = map.get(A.substring(index, i));
                if(count==null){
                    map.put(A.substring(index, i), 1);
                }else{
                    map.put(A.substring(index, i), count+1);
                }
                if(i+1<A.length()){
                    index = i+1;
                }
            }else if(i==A.length()-1){
                Integer count = map.get(A.substring(index));
                if(count==null){
                    map.put(A.substring(index), 1);
                }else{
                    map.put(A.substring(index), count+1);
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值