【Lintcode】856. Sentence Similarity

题目地址:

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是最长字符串长度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值