[LeetCode] Uncommon Words from Two Sentences

아르당·2026년 3월 9일

LeetCode

목록 보기
190/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문장은 한 칸 띄어쓰기로 구분된 단어들의 나열되었고, 각 단어는 모두 소문자로만 구성된다.
한 문장에 딱 한 번만 나오고 다른 문장에는 전혀 나오지 않는 단어는 흔하지 않은 단어라고 한다.
두 개의 문장 s1과 s2가 주어졌을 때, 두 문장에서 공토으로 사용되지 않은 단어들의 리스트를 반환해라. 순서는 상관없다.

Example

#1
Input: s1 = "this apple is sweet", s2 = "this apple is sour"
Output: ["sweet", "sour"]
Explanation: 단어 "sweet"는 오직 s1에만 나타나고, 단어 "sour"는 오직 s2에서만 나타난다.

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

Constraints

  • 1 <= s1.length, s2.length <= 200
  • s1과 s2는 영어 소문자와 공백으로 구성된다.
  • s1과 s2는 맨 앞과 맨 뒤에 공백은 없다.
  • s1과 s2에 있는 모든 단어는 단일 공백으로 구분된다.

Solved

class Solution {
    public String[] uncommonFromSentences(String s1, String s2) {
        Map<String, Integer> count = new HashMap<>();

        for(String s : (s1 + " " + s2).split(" ")){
            count.put(s, count.getOrDefault(s, 0) + 1);
        }

        ArrayList<String> result = new ArrayList<>();

        for(String c : count.keySet()){
            if(count.get(c) == 1){
                result.add(c);
            }
        }

        return result.toArray(new String[0]);
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글