1.问题描述
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"]
要求:
2.我自己的解题思路
public String[] uncommonFromSentences(String A, String B) { List<String> list = new LinkedList<>(); String[] aStr = A.split(" "); String[] bStr = B.split(" "); List<String> aList = Arrays.asList(aStr); List<String> bList = Arrays.asList(bStr); Collections.sort(aList); Collections.sort(bList); String tmp1 = ""; for (Iterator<String> iterator = aList.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); if (!tmp1.equals(string)) { if (!bList.contains(string)) { list.add(string); tmp1 = string; } } else { list.remove(tmp1); } } String tmp2 = ""; for (Iterator<String> iterator = bList.iterator(); iterator.hasNext();) { String string = (String) iterator.next(); if (!tmp2.equals(string)) { if (!aList.contains(string)) { list.add(string); tmp2 = string; } } else { list.remove(tmp2); } } String[] result = new String[list.size()]; list.toArray(result); return result; }
3.应该要用的解题思路:HashMap
使用HashMap集合将A和B两个句子中的所有单词作为键key,将每个单词对应的出现次数作为值value。
count.getOrDefault(word, 0)的意思是,如果集合中已经存在word这个键,就使用其对应的value值,否则,使用默认的值0,用来判断单词出现的次数。
然后统计HashMap集合中每个单词对应的值value,如果等于1就说明只出现了一次,然后加入到结果集ans中即可。
时间复杂度:O(M+N),M是A的复杂度,N是B的复杂度。
空间复杂度:O(M+N),使用的HashMap集合count所占用的空间。
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()]); } }
原文:https://www.cnblogs.com/BigJunOba/p/9509379.html