java solution using map!


  • 0
    T
    class Solution {
        public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
            if(words1.length!=words2.length){
                return false;
            }
            
            HashMap<String,Set<String>> map = new HashMap<>();
            for(String[] ele:pairs){
                if(!map.containsKey(ele[0])){
                    map.put(ele[0],new HashSet<>());
                }
                if(!map.containsKey(ele[1])){
                    map.put(ele[1],new HashSet<>());
                }
                
                map.get(ele[0]).add(ele[1]);
                map.get(ele[1]).add(ele[0]);
            }
            
            for(int i=0;i<words1.length;i++){
                if(words1[i].equals(words2[i])){
                    continue;
                }
                
                if(!map.containsKey(words1[i]) || !map.get(words1[i]).contains(words2[i])){
                    return false;
                }
            }
            
            return true;
        }
    }
    

Log in to reply
 

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