Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Time Complexity: O(N + P) Space Complexity : O(P)
- *
- * N = length of words1. P = size of pairs.
- */
- class Solution {
- public boolean areSentencesSimilar(String[] words1, String[] words2, String[][] pairs) {
- if (words1 == null || words2 == null || words1.length != words2.length) {
- return false;
- }
- Map<String, Set<String>> pairsMap = new HashMap();
- for (String[] pair : pairs) {
- if (!pairsMap.containsKey(pair[0])) {
- pairsMap.put(pair[0], new HashSet<String>());
- }
- if (!pairsMap.containsKey(pair[1])) {
- pairsMap.put(pair[1], new HashSet<String>());
- }
- pairsMap.get(pair[0]).add(pair[1]);
- pairsMap.get(pair[1]).add(pair[0]);
- }
- for (int i = 0; i < words1.length; i++) {
- if (words1[i].equals(words2[i])) {
- continue;
- }
- if (!pairsMap.containsKey(words1[i])) {
- return false;
- }
- if (!pairsMap.get(words1[i]).contains(words2[i])) {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement