题目标签: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]);
}
}
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/