https://leetcode.com/problems/uncommon-words-from-two-sentences

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.

解题思路:

简单但是蛋疼的一道题目。读题目后发现,这里的uncommon,其实就是在A和B里面加起来只出现一次的。

先用map统计次数,然后拿出只出现一次的词,最后形成array。

class Solution {
public String[] uncommonFromSentences(String A, String B) {
Map<String, Integer> map = new HashMap<String, Integer>();
String[] a1 = A.split(" ");
String[] b1 = B.split(" ");
for (String str : a1) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
for (String str : b1) {
map.put(str, map.getOrDefault(str, 0) + 1);
} List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : map.entrySet())
{
if (entry.getValue() == 1) {
list.add(entry.getKey());
}
}
String[] res = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i] = list.get(i);
}
return res;
}
}

有人写的更简洁,逻辑是一样的

https://leetcode.com/problems/uncommon-words-from-two-sentences/discuss/158967/C%2B%2BJavaPython-Easy-Solution-with-Explanation

最新文章

  1. 记住密码超简单实现(C#)
  2. 【Unity3D基础教程】给初学者看的Unity教程(五):详解Unity3D中的协程(Coroutine)
  3. Window memcache 使用
  4. 新手Oracle安装及使用入门
  5. 项目解析- JspLibrary - part3
  6. ARM异常中断处理
  7. [VB.NET]拖动操作的技术基础
  8. 变态最大值--nyoj题目811
  9. Git操作流水账
  10. 学习笔记:javascript内置对象:数组对象
  11. js模块加载详解
  12. 【洛谷P1706全排列问题】
  13. 前端之css样式(选择器)。。。
  14. Linux用管道命令对文件的移动
  15. [leetcode 14]Longest Common Prfix
  16. MAC连接安卓手机通过adb指令安装apk
  17. yii源码一 -- CComponent
  18. 不常用但很有用的git show 和 git blame
  19. swift,NSUserDefaults的swift化封装
  20. 切换python版本

热门文章

  1. 《Java设计模式》之构建者模式
  2. 【BZOJ4519】[Cqoi2016]不同的最小割 最小割树
  3. java中随机生成汉字
  4. 九度OJ 1024:畅通工程 (最小生成树)
  5. mysql系列之4.mysql字符集
  6. HTML 学习笔记 JQuery(animation)
  7. 【Android】Android中AlertDialog对话框的使用实例
  8. 怎样拆分View Controller进而实现轻量级的View Controller[UIKit]
  9. Java for LeetCode 100 Same Tree
  10. com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry &#39;88888888&#39; for key &#39;PRIMARY&#39;