Sentence Similarity

유승선 ·2024년 3월 10일
0

LeetCode

목록 보기
110/115

원래는 난이도 easy 등급은 풀지도 않았는데. 자바 문법에 더 익숙해지는 시간이라서 헷갈렸던 함수 개념이 생각나고 그랬다.

C++에서도 map 을 만들 때 value 값으로 vector 나 set 을 사용하기도 하는데 Java 에서도 똑같은 상황에서 이 함수를 사용한다.

이번에 배운 함수는 computeIfAbsent()
설명

예전에 실험 했을 때 이렇게 자료구조를 사용하는 Map의 경우 value 값을 넣을 때 자료구조를 안만들어 주면 ERROR 가 나오기도 했다.

computeIfAbsent 로 자료구조를 만들어주고 .add 함수로 넣어주면 될거같다.

class Solution {
public
    boolean areSentencesSimilar(String[] sentence1, String[] sentence2,List<List<String>> similarPairs) {
        if (sentence1.length != sentence2.length) {
            return false;
        }
        Map<String, Set<String>> wordToSimilarWords = new HashMap<>();
        for (List<String> pair : similarPairs) {
            wordToSimilarWords.computeIfAbsent(pair.get(0), value->new HashSet<String>())
                .add(pair.get(1));
            wordToSimilarWords.computeIfAbsent(pair.get(1), value->new HashSet<String>())
                .add(pair.get(0));
        }

        for (int i = 0; i < sentence1.length; i++) {
            // If the words are equal, continue.
            if (sentence1[i].equals(sentence2[i])) {
                continue;
            }
            // If the words form a similar pair, continue.
            if (wordToSimilarWords.containsKey(sentence1[i]) &&
                wordToSimilarWords.get(sentence1[i]).contains(sentence2[i])) {
                continue;
            }
            return false;
        }

        return true;
    }
}
profile
성장하는 사람

0개의 댓글