HashMap with HashSet(Java)


  • 0
    class Solution {
        public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
            Map<String, Set<String>> table = new HashMap<String, Set<String>>();
            int len1 = words1.length;
            int len2 = words2.length;
            if(len1 != len2)
                return false;
            for(String [] pair : pairs) {
                if(!table.containsKey(pair[0])) {
                    Set<String> set = new HashSet<String>();
                    table.put(pair[0], set);
                }                
                table.get(pair[0]).add(pair[1]);
            }
            for(int i = 0; i < len1; i++) {
                if(!(words1[i].equals(words2[i]) 
                     || match(table, words1[i], words2[i]) 
                     || match(table, words2[i], words1[i])))
                    return false;
            }
            return true;
        }
                       
        private boolean match(Map<String, Set<String>> table, String word1, String word2) {
            if(table.containsKey(word1)) 
                return table.get(word1).contains(word2);
            return false;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.