Leetcode

Count Common Words With One Occurrence

  • Time:O(n)
  • Space:O(n)

C++

class Solution {
 public:
  int countWords(vector<string>& words1, vector<string>& words2) {
    unordered_map<string, int> count;

    for (const string& word : words1)
      ++count[word];

    for (const string& word : words2)
      if (count.count(word) && count[word] < 2)
        --count[word];

    return count_if(begin(count), end(count),
                    [](const auto& c) { return c.second == 0; });
  }
};

JAVA

class Solution {
  public int countWords(String[] words1, String[] words2) {
    Map<String, Integer> count = new HashMap<>();

    for (final String word : words1)
      count.merge(word, 1, Integer::sum);

    for (final String word : words2)
      if (count.containsKey(word) && count.get(word) < 2)
        count.merge(word, -1, Integer::sum);

    return (int) count.values().stream().filter(v -> v == 0).count();
  }
}

Python

class Solution:
  def countWords(self, words1: List[str], words2: List[str]) -> int:
    count = Counter(words1)

    for word in words2:
      if word in count and count[word] < 2:
        count[word] -= 1

    return sum(value == 0 for value in count.values())