算法题 |
---|
算法题 |
---|
句子 是一串由空格分隔的单词。每个 单词 仅由小写字母组成。
如果某个单词在其中一个句子中恰好出现一次,在另一个句子中却 没有出现 ,那么这个单词就是 不常见的 。
给你两个 句子 s1 和 s2 ,返回所有 不常用单词 的列表。返回列表中单词可以按 任意顺序 组织。
示例1:
输入:s1 = "apple apple", s2 = "banana"
输出:["banana"]
示例2:
输入:s1 = "this apple is sweet", s2 = "this apple is sour"
输出:["sweet","sour"]
提示:
每个不常见的单词总共只出现一次。
我们可以统计每个单词的出现次数,然后返回恰好出现一次的单词。
代码:
public class Solution {
public string[] UncommonFromSentences(string s1, string s2) {
string[] sa = s1.Split(' ');
string[] sb = s2.Split(' ');
Dictionary<string,int> dic = new Dictionary<string,int>();
foreach(var s in sa)
{
if(!dic.ContainsKey(s))
{
dic.Add(s,1);
}
else
{
dic[s]++;
}
}
foreach(var s in sb)
{
if(!dic.ContainsKey(s))
{
dic.Add(s,1);
}
else
{
dic[s]++;
}
}
List<string> ret = new List<string>();
foreach(var item in dic)
{
if(item.Value == 1)
{
ret.Add(item.Key);
}
}
return ret.ToArray();
}
}
执行结果
通过
执行用时:140 ms,在所有 C# 提交中击败了42.14%的用户
内存消耗:41.9 MB,在所有 C# 提交中击败了14.70%的用户
思路解析 我们可以遍历该序列,并记录当前分组的长度。
如果下一个字符与当前字符不同,或者已经枚举到字符串尾部,就说明当前字符为当前分组的尾部。
每次找到当前分组的尾部时,如果该分组长度达到 33,我们就将其加入答案。
代码:
class Solution {
public String[] uncommonFromSentences(String A, String B) {
Map<String, Integer> count = new HashMap();
for (String word: A.split(" "))
count.put(word, count.getOrDefault(word, 0) + 1);
for (String word: B.split(" "))
count.put(word, count.getOrDefault(word, 0) + 1);
List<String> ans = new LinkedList();
for (String word: count.keySet())
if (count.get(word) == 1)
ans.add(word);
return ans.toArray(new String[ans.size()]);
}
}
执行结果
通过
执行用时:2 ms,在所有 Java 提交中击败了99.41%的用户
内存消耗:38.4 MB,在所有 Java 提交中击败了5.53%的用户
复杂度分析
时间复杂度:O( M+N )其中 M,N 分别是 A 和 B 的长度。
空间复杂度:O(M+N)
C#
和 Java
两种编程语言进行解题