题目地址:
https://www.lintcode.com/problem/sentence-similarity/description
给定两个字符串数组 A 1 A_1 A1和 A 2 A_2 A2,再给定若干pair,问是否对于任何 i i i都有 A 1 [ i ] A_1[i] A1[i]和 A 2 [ i ] A_2[i] A2[i]存在于同一个pair中。如果两个 A 1 [ i ] = A 2 [ i ] A_1[i]=A_2[i] A1[i]=A2[i]也视为成立。
用哈希表存双向边,然后同时遍历两个数组,对每个位置进行判断。代码如下:
import java.util.*;
public class Solution {
/**
* @param words1: a list of string
* @param words2: a list of string
* @param pairs: a list of string pairs
* @return: return a boolean, denote whether two sentences are similar or not
*/
public boolean isSentenceSimilarity(String[] words1, String[] words2, List<List<String>> pairs) {
// write your code here
Map<String, Set<String>> map = new HashMap<>();
if (words1.length != words2.length) {
return false;
}
for (List<String> pair : pairs) {
String s1 = pair.get(0), s2 = pair.get(1);
map.putIfAbsent(s1, new HashSet<>());
map.putIfAbsent(s2, new HashSet<>());
map.get(s1).add(s2);
map.get(s2).add(s1);
}
for (int i = 0; i < words1.length; i++) {
if (words1[i].equals(words2[i])) {
continue;
}
if (!map.get(words1[i]).contains(words2[i])) {
return false;
}
}
return true;
}
}
时空复杂度 O ( n l ) O(nl) O(nl), n n n为数组长度, l l l是最长字符串长度。