5922. 統計出現過一次的公共字符串
給你兩個字符串數組?words1?和?words2?,請你返回在兩個字符串數組中 都恰好出現一次?的字符串的數目。
示例 1:輸入:words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
輸出:2
解釋:
- "leetcode" 在兩個數組中都恰好出現一次,計入答案。
- "amazing" 在兩個數組中都恰好出現一次,計入答案。
- "is" 在兩個數組中都出現過,但在 words1 中出現了 2 次,不計入答案。
- "as" 在 words1 中出現了一次,但是在 words2 中沒有出現過,不計入答案。
所以,有 2 個字符串在兩個數組中都恰好出現了一次。示例 2:輸入:words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
輸出:0
解釋:沒有字符串在兩個數組中都恰好出現一次。示例 3:輸入:words1 = ["a","ab"], words2 = ["a","a","a","ab"]
輸出:1
解釋:唯一在兩個數組中都出現一次的字符串是 "ab" 。
提示:
- 1 <= words1.length, words2.length <= 1000
- 1 <= words1[i].length, words2[j].length <= 30
- words1[i] 和?words2[j]?都只包含小寫英文字母。
解題思路
- 使用map記錄下每個單詞出現的次數,key為單詞字符串,value為其對應出現的次數
- 遍歷兩個字符串數組,統計兩個字符串數組中,每一個單詞出現次數
- 遍歷word1數組中的所有單詞,只有當word1中出現次數為1的單詞,我們才需要在word2數組檢查該單詞是否存在,并且檢查該單詞在word2中是否只出現一次,如果滿足條件的話,則說明這是一個在兩個字符串數組中 都恰好出現一次?的字符串。
代碼
class Solution {
public:int countWords(vector<string>& words1, vector<string>& words2) {map<string,int> m1,m2;for (int i = 0; i < words1.size(); ++i) {m1[words1[i]]++;}for (int i = 0; i < words2.size(); ++i) {m2[words2[i]]++;}int res(0);for(auto item:m1){if (item.second==1&&m2[item.first]==1)res++;}return res;}
};