LeetCode-Uncommon Words from Two Sentences
原创
©著作权归作者所有:来自51CTO博客作者BeHelium的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description:
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 and B both contain only spaces and lowercase letters.
题意:给定两个字符串,字符串中包含用空格分隔开的单词;要求找出所有在两个串中只出现过一次的单词;
解法:我们可以将两个串中的单词及其出现的次数作为键值对存储在哈希表中,这样遍历哈希表返回只出现一次的键;
Java
class Solution {
public String[] uncommonFromSentences(String A, String B) {
StringBuilder result = new StringBuilder();
Map<String, Integer> words = new HashMap<>();
getWords(words, A);
getWords(words, B);
for (String word : words.keySet()) {
if (words.get(word) == 1) {
result.append(word + "\u0020");
}
}
return result.length() == 0 ? new String[] {} : result.toString().split("\u0020");
}
private void getWords(Map<String, Integer> words, String s) {
for (String word : s.split("\u0020")) {
words.put(word, words.getOrDefault(word, 0) + 1);
}
}
}