[LeetCode] Uncommon Words from Two Sentences

준규·2022년 12월 8일

1.문제


A sentence is a string of single-space separated words where each word consists only of lowercase letters.

A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.

Given two sentences s1 and s2, return a list of all the uncommon words. You may return the answer in any order.


소문자로 이루어진 s1, s2 문자열이 주어질 때 s1, s2 어느쪽에도 중복이 없는 단어 배열을 리턴하는 문제이다.


Example 1

Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet","sour"]

Example 2

Input: s1 = "apple apple", s2 = "banana"
Output: ["banana"]

Constraints:

  • 1 <= s1.length, s2.length <= 200
  • s1 and s2 consist of lowercase English letters and spaces.
  • s1 and s2 do not have leading or trailing spaces.
  • All the words in s1 and s2 are separated by a single space.

2.풀이

  1. 각 문자열에서 단어기준으로 잘라서 배열로 만들어준다.
  2. 각 단어의 갯수를 센다
  3. 양쪽 문자열 갯수 객체에 1개씩만 존재하는지 체크한다.

/**
 * @param {string} s1
 * @param {string} s2
 * @return {string[]}
 */
var uncommonFromSentences = function(s1, s2) {
    s1 = s1.split(' ');
    s2 = s2.split(' ');
    const result = [];
    let map1 = {};
    let map2 = {};

    s1.forEach((word) => {
        map1[word] ? map1[word] = map1[word] + 1 : map1[word] = 1;
    })

    s2.forEach((word) => {
        map2[word] ? map2[word] = map2[word] + 1 : map2[word] = 1;
    })
    

    for(let key in map1) {
        if(map1[key] === 1) {
            if(!map2[key]) result.push(key)
        }
    }

    for(let key in map2) {
        if(map2[key] === 1) {
             if(!map1[key]) result.push(key)
        }
    }

    return result
};

3.결과

profile
안녕하세요 :)

0개의 댓글