Uncommon Words from Two Sentences
2024-10-21 03:41:18
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:
0 <= A.length <= 200
0 <= B.length <= 200
A
andB
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
最新文章
- 记住密码超简单实现(C#)
- 【Unity3D基础教程】给初学者看的Unity教程(五):详解Unity3D中的协程(Coroutine)
- Window memcache 使用
- 新手Oracle安装及使用入门
- 项目解析- JspLibrary - part3
- ARM异常中断处理
- [VB.NET]拖动操作的技术基础
- 变态最大值--nyoj题目811
- Git操作流水账
- 学习笔记:javascript内置对象:数组对象
- js模块加载详解
- 【洛谷P1706全排列问题】
- 前端之css样式(选择器)。。。
- Linux用管道命令对文件的移动
- [leetcode 14]Longest Common Prfix
- MAC连接安卓手机通过adb指令安装apk
- yii源码一 -- CComponent
- 不常用但很有用的git show 和 git blame
- swift,NSUserDefaults的swift化封装
- 切换python版本
热门文章
- 《Java设计模式》之构建者模式
- 【BZOJ4519】[Cqoi2016]不同的最小割 最小割树
- java中随机生成汉字
- 九度OJ 1024:畅通工程 (最小生成树)
- mysql系列之4.mysql字符集
- HTML 学习笔记 JQuery(animation)
- 【Android】Android中AlertDialog对话框的使用实例
- 怎样拆分View Controller进而实现轻量级的View Controller[UIKit]
- Java for LeetCode 100 Same Tree
- com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry &#39;88888888&#39; for key &#39;PRIMARY&#39;