LeetCode Solutions

884. Uncommon Words from Two Sentences

Time:

Space:

			

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;
  }
};
			

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]);
  }
}
			

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]