734. Sentence Similarity

LeetCode easy original: C# #array #csharp #easy #hash-table #leetcode #string
Der Aufgabentext wird für die gewählte Sprache aus dem Russischen übersetzt. Code bleibt unverändert.

Мы можем представить предложение в виде Arrayа слов, наBeispiel, предложение "I am happy with leetcode" можно представить как arr = ["I", "am",happy", "with", "leetcode"].

given два предложения sentence1 и sentence2, каждое из которых представлено в виде Arrayа строк, и Array пар строк similarPairs, где similarPairs[i] = [xi, yi] указывает, что два слова xi и yi похожи. returnsся true, если предложения sentence1 и sentence2 похожи, или false, если они не похожи. Два предложения похожи, если: у них одинаковая длина (т.е, Заметьте, что слово всегда похоже само на себя, также обратите внимание, что отношение сходства не является транзитивным. НаBeispiel, если слова a и b похожи, а слова b и c похожи, то a и c не обязательно похожи.

Beispiel:

Input: sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]

Output: true

C# Lösung

zugeordnet/original
using System;
using System.Collections.Generic;
public class Solution {
    public bool AreSentencesSimilar(string[] sentence1, string[] sentence2, IList<IList<string>> similarPairs) {
        if (sentence1.Length != sentence2.Length) {
            return false;
        }
        var similar = new Dictionary<string, HashSet<string>>();
        foreach (var pair in similarPairs) {
            var x = pair[0];
            var y = pair[1];
            if (!similar.ContainsKey(x)) {
                similar[x] = new HashSet<string>();
            }
            if (!similar.ContainsKey(y)) {
                similar[y] = new HashSet<string>();
            }
            similar[x].Add(y);
            similar[y].Add(x);
        }
        for (int i = 0; i < sentence1.Length; i++) {
            var w1 = sentence1[i];
            var w2 = sentence2[i];
            if (w1 != w2 && (!similar.ContainsKey(w1) || !similar[w1].Contains(w2))) {
                return false;
            }
        }
        return true;
    }
}

C++ Lösung

Auto-Entwurf, vor dem Einreichen prüfen
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public bool AreSentencesSimilar(vector<string> sentence1, vector<string> sentence2, IList<vector<string>> similarPairs) {
        if (sentence1.size() != sentence2.size()) {
            return false;
        }
        var similar = new unordered_map<string, HashSet<string>>();
        foreach (var pair in similarPairs) {
            var x = pair[0];
            var y = pair[1];
            if (!similar.count(x)) {
                similar[x] = new HashSet<string>();
            }
            if (!similar.count(y)) {
                similar[y] = new HashSet<string>();
            }
            similar[x].push_back(y);
            similar[y].push_back(x);
        }
        for (int i = 0; i < sentence1.size(); i++) {
            var w1 = sentence1[i];
            var w2 = sentence2[i];
            if (w1 != w2 && (!similar.count(w1) || !similar[w1].Contains(w2))) {
                return false;
            }
        }
        return true;
    }
}

Java Lösung

zugeordnet/original
import java.util.*;

public class Solution {
    public boolean areSentencesSimilar(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
        if (sentence1.length != sentence2.length) {
            return false;
        }
        
        Map<String, Set<String>> similar = new HashMap<>();
        for (List<String> pair : similarPairs) {
            String x = pair.get(0);
            String y = pair.get(1);
            similar.computeIfAbsent(x, k -> new HashSet<>()).add(y);
            similar.computeIfAbsent(y, k -> new HashSet<>()).add(x);
        }
        
        for (int i = 0; i < sentence1.length; i++) {
            String w1 = sentence1[i];
            String w2 = sentence2[i];
            if (!w1.equals(w2) && (!similar.containsKey(w1) || !similar.get(w1).contains(w2))) {
                return false;
            }
        }
        
        return true;
    }
}

JavaScript Lösung

zugeordnet/original
var areSentencesSimilar = function(sentence1, sentence2, similarPairs) {
    if (sentence1.length !== sentence2.length) {
        return false;
    }

    const similar = new Map();
    for (const [x, y] of similarPairs) {
        if (!similar.has(x)) similar.set(x, new Set());
        if (!similar.has(y)) similar.set(y, new Set());
        similar.get(x).add(y);
        similar.get(y).add(x);
    }

    for (let i = 0; i < sentence1.length; i++) {
        const w1 = sentence1[i], w2 = sentence2[i];
        if (w1 !== w2 && (!similar.has(w1) || !similar.get(w1).has(w2))) {
            return false;
        }
    }

    return true;
};

Python Lösung

zugeordnet/original
def areSentencesSimilar(sentence1, sentence2, similarPairs):
    if len(sentence1) != len(sentence2):
        return False
    
    similar = {}
    for x, y in similarPairs:
        if x not in similar:
            similar[x] = set()
        if y not in similar:
            similar[y] = set()
        similar[x].add(y)
        similar[y].add(x)
    
    for w1, w2 in zip(sentence1, sentence2):
        if w1 != w2 and (w1 not in similar or w2 not in similar[w1]):
            return False
    
    return True

Go Lösung

zugeordnet/original
package main

func areSentencesSimilar(sentence1 []string, sentence2 []string, similarPairs [][]string) bool {
    if len(sentence1) != len(sentence2) {
        return false
    }

    similar := make(map[string]map[string]bool)
    for _, pair := range similarPairs {
        x, y := pair[0], pair[1]
        if _, exists := similar[x]; !exists {
            similar[x] = make(map[string]bool)
        }
        if _, exists := similar[y]; !exists {
            similar[y] = make(map[string]bool)
        }
        similar[x][y] = true
        similar[y][x] = true
    }

    for i := 0; i < len(sentence1); i++ {
        w1, w2 := sentence1[i], sentence2[i]
        if w1 != w2 && (!similar[w1][w2]) {
            return false
        }
    }

    return true
}

Algorithm

Проверьте, равны ли длины предложений sentence1 и sentence2. Если нет, return false.

Создайте словарь для хранения всех пар похожих слов.

Проверьте каждую пару слов из предложений sentence1 и sentence2 на схожесть, используя словарь и правило, что слово всегда похоже на само себя.

😎

Stellen zu dieser Aufgabe

aktive Stellen with overlapping task tags are angezeigt.

Alle Stellen
Es gibt noch keine aktiven Stellen.