734. Sentence Similarity
Given two sentences words1, words2 (each represented as an array of strings), and a list of similar word pairs pairs, determine if two sentences are similar. For example, "great acting skills" and "fine drama talent" are similar, if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]. Note that the similarity relation is not transitive. For example, if "great" and "fine" are similar, and "fine" and "good" are similar, "great" and "good" are not necessarily similar. However, similarity is symmetric. For example, "great" and "fine" being similar is the same as "fine" and "great" being similar. Also, a word is always similar with itself. For example, the sentences words1 = ["great"], words2 = ["great"], pairs = [] are similar, even though there are no specified similar word pairs. Finally, sentences can only be similar if they have the same number of words. So a sentence like words1 = ["great"] can never be similar to words2 = ["doubleplus","good"]. If the size of the words 1 and words2 are different Then false If their size is the same , then we do another Condition check , "great acting skills" and "fine drama talent" are similar, if the similar word pairs are pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]]. First, we use a hash map to store the information from Pairs for example: key is great, value is fine So we traverse the word1 and word 2 with the help of this hash map class Solution { public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) { // if the size of the words1 and words2 are not the same, return false if(words1.length != words2.length) return false; HashMap<String, List<String>> map = new HashMap<>(); // build map from pairs for(String[] pair : pairs){ String first = pair[0]; String second = pair[1]; // List<String> list = map.get(first); // if(list == null){ // map.put(first, new ArrayList<>()); // } // list.add(second); // map.put(first, list); if(!map.containsKey(first)){ map.put(first, new ArrayList<>()); } List<String> list = map.get(first); list.add(second); } // traverse the words1 and words2 with the help of the map for(int i = 0; i < words1.length; i++){ String first = words1[i]; String second = words2[i]; // if map has first, check if the second is in the list of the first in the map, vice versa // else return false // corner case : if the first and second are the same word, then its similar as defined in teh above if(first.equals(second)) continue; if(map.containsKey(first) && map.get(first).contains(second)) continue; if(map.containsKey(second) && map.get(second).contains(first)) continue; else return false; } return true; } } // , "great acting skills" and "fine drama talent" are similar, // if the similar word pairs are // pairs = [["great", "fine"], ["acting","drama"], ["skills","talent"]].
posted on 2018-09-20 18:30 猪猪🐷 阅读(164) 评论(0) 收藏 举报
浙公网安备 33010602011771号