首页 > 其他 > 详细

LeetCode 884. Uncommon Words from Two Sentences (两句话中的不常见单词)

时间:2019-04-28 23:59:58      阅读:248      评论:0      收藏:0      [点我收藏+]

题目标签:HashMap

  题目给了我们两个句子,让我们找出不常见单词,只出现过一次的单词就是不常见单词。

  把A 和 B 里的word 都存入 map,记录它们出现的次数。之后遍历map,把只出现过一次的存入 result。

 

Java Solution:

Runtime: 3 ms, faster than 89.90% 

Memory Usage: 37.2 MB, less than 85.88%

完成日期:03/27/2019

关键点:hashmap

class Solution 
{
    public String[] uncommonFromSentences(String A, String B) 
    {
        Map<String, Integer> map = new HashMap<>();
        List<String> result = new ArrayList<>();
        
        // put each work into map
        for(String str : (A + " " + B).split(" "))
        {
            map.put(str, map.getOrDefault(str, 0) + 1);   
        }
        
        // iterate map to put all the word with value 1 into arraylist
        for(String str : map.keySet())
        {
            if(map.get(str) == 1)
                result.add(str);
        }
        
        return result.toArray(new String[0]);
    }
}

参考资料:https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/?currentPage=1&orderBy=recent_activity&query=

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

LeetCode 884. Uncommon Words from Two Sentences (两句话中的不常见单词)

原文:https://www.cnblogs.com/jimmycheng/p/10787673.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!