Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.5 kB
24
Indexable
Never
public class Solution {
    public int solve(ArrayList<String> A, ArrayList<String> B) {
        // Find the hashvalue for each string in a ArrayList A
        int n=A.size();
        HashMap<Long,Integer> hm1=new HashMap<Long,Integer>();
        for(int i=0;i<n;i++)
        {
            int n1=A.get(i).length();
            long hash=0;
            for(int j=0;j<n1;j++)
            {
                hash+=((A.get(i).charAt(j)-'a'+1)*(((long)Math.pow(29,n1-j-1))));
            }
            hm1.put(hash,hm1.getOrDefault(hash,0)+1);
        }
        
        // Find the hashvalue for each string in Arraylist B
        
        int m=B.size();
        HashMap<Long,Integer> hm2=new HashMap<Long,Integer>();
        for(int i=0;i<m;i++)
        {
            int m1=B.get(i).length();
            long hash=0;
            for(int j=0;j<m1;j++)
            {
                hash+=((B.get(i).charAt(j) - 'a'+1)*(((long)Math.pow(29,m1-j-1))));
            }
            hm2.put(hash,hm2.getOrDefault(hash,0)+1);
        }
        
        // Use advance forloop to take each element in the hashmap1 and check its freq is 1 then check the same is in hashmap2 
        int ans=0;
       // System.out.println("hashmap1 : "+hm1+"hashmap 2 :"+hm2);
        for(Map.Entry<Long,Integer> set : hm1.entrySet())
        {
            if(set.getValue() == 1 && hm2.containsKey(set.getKey()) && hm2.get(set.getKey()) == 1)
            {
                ans++;
            }
        }
        
        return ans;
    }
}