Skip to content

Latest commit

 

History

History
133 lines (107 loc) · 3.83 KB

File metadata and controls

133 lines (107 loc) · 3.83 KB

中文文档

Description

Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.

 

Example 1:

Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
Explanation:
- "leetcode" appears exactly once in each of the two arrays. We count this string.
- "amazing" appears exactly once in each of the two arrays. We count this string.
- "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
- "as" appears once in words1, but does not appear in words2. We do not count this string.
Thus, there are 2 strings that appear exactly once in each of the two arrays.

Example 2:

Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
Output: 0
Explanation: There are no strings that appear in each of the two arrays.

Example 3:

Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"]
Output: 1
Explanation: The only string that appears exactly once in each of the two arrays is "ab".

 

Constraints:

  • 1 <= words1.length, words2.length <= 1000
  • 1 <= words1[i].length, words2[j].length <= 30
  • words1[i] and words2[j] consists only of lowercase English letters.

Solutions

Python3

class Solution:
    def countWords(self, words1: List[str], words2: List[str]) -> int:
        cnt1 = Counter(words1)
        cnt2 = Counter(words2)
        return sum(cnt2[k] == 1 for k, v in cnt1.items() if v == 1)

Java

class Solution {
    public int countWords(String[] words1, String[] words2) {
        Map<String, Integer> cnt1 = count(words1);
        Map<String, Integer> cnt2 = count(words2);
        int ans = 0;
        for (String w : words1) {
            if (cnt1.getOrDefault(w, 0) == 1 && cnt2.getOrDefault(w, 0) == 1) {
                ++ans;
            }
        }
        return ans;
    }

    private Map<String, Integer> count(String[] words) {
        Map<String, Integer> cnt = new HashMap<>();
        for (String w : words) {
            cnt.put(w, cnt.getOrDefault(w, 0) + 1);
        }
        return cnt;
    }
}

C++

class Solution {
public:
    int countWords(vector<string>& words1, vector<string>& words2) {
        unordered_map<string, int> cnt1;
        unordered_map<string, int> cnt2;
        for (auto& w : words1) cnt1[w]++;
        for (auto& w : words2) cnt2[w]++;
        int ans = 0;
        for (auto& w : words1) ans += (cnt1[w] == 1 && cnt2[w] == 1);
        return ans;
    }
};

Go

func countWords(words1 []string, words2 []string) int {
	cnt1 := map[string]int{}
	cnt2 := map[string]int{}
	for _, w := range words1 {
		cnt1[w]++
	}
	for _, w := range words2 {
		cnt2[w]++
	}
	ans := 0
	for _, w := range words1 {
		if cnt1[w] == 1 && cnt2[w] == 1 {
			ans++
		}
	}
	return ans
}

...