Problem
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.
Solution: HashTable
Time complexity: O(m+n)
Space complexity: O(m+n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Solution { public: vector<string> uncommonFromSentences(string A, string B) { istringstream ss(A + " " + B); unordered_map<string, int> counts; string s; while (ss >> s) ++counts[s]; vector<string> ans; for (const auto& p : counts) if (p.second == 1) ans.push_back(p.first); return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment