Skip to content

884. Uncommon Words from Two Sentences 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  vector<string> uncommonFromSentences(string A, string B) {
    vector<string> ans;
    unordered_map<string, int> count;
    istringstream iss(A + ' ' + B);

    while (iss >> A)
      ++count[A];

    for (const auto& [word, freq] : count)
      if (freq == 1)
        ans.push_back(word);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public String[] uncommonFromSentences(String A, String B) {
    List<String> ans = new ArrayList<>();
    Map<String, Integer> count = new HashMap<>();

    for (final String word : (A + ' ' + B).split(" "))
      count.put(word, count.getOrDefault(word, 0) + 1);

    for (final String word : count.keySet())
      if (count.get(word) == 1)
        ans.add(word);

    return ans.toArray(new String[0]);
  }
}
1
2
3
4
class Solution:
  def uncommonFromSentences(self, A: str, B: str) -> List[str]:
    count = Counter((A + ' ' + B).split())
    return [word for word, freq in count.items() if freq == 1]
Back to top