【Leetcode】2085. Count Common Words With One Occurrence

题目地址:

https://leetcode.com/problems/count-common-words-with-one-occurrence/

给定两个字符串数组 A A A B B B,求有多少个字符串在各自数字里只出现一次。

用两个哈希表计个数即可。代码如下:

import java.util.HashMap;
import java.util.Map;

public class Solution {
    
    
    public int countWords(String[] words1, String[] words2) {
    
    
        Map<String, Integer> map1 = new HashMap<>(), map2 = new HashMap<>();
        for (String s : words1) {
    
    
            map1.put(s, map1.getOrDefault(s, 0) + 1);
        }
        for (String s : words2) {
    
    
            map2.put(s, map2.getOrDefault(s, 0) + 1);
        }
    
        int res = 0;
        for (Map.Entry<String, Integer> entry : map1.entrySet()) {
    
    
            String s = entry.getKey();
            int cnt = entry.getValue();
            if (cnt == 1 && map2.getOrDefault(s, 0) == 1) {
    
    
                res++;
            }
        }
        
        return res;
    }
}

时空复杂度 O ( ( l A + l B ) l ) O((l_A+l_B)l) O((lA+lB)l) l l l为字符串最长长度。

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/121607281