[LeetCode] Destination City

아르당·4일 전

LeetCode

목록 보기
300/303
post-thumbnail

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

Problem

배열 paths가 주어졌을 때, paths[i] = [cityAi, cityBi]는 cityAi에서 cityBi로 가는 직접적인 경로가 존재하는 것을 의미한다.
목적지 도시, 즉 다른 도시로 통하는 길이 없는 도시를 반환해라.

paths의 그래프는 루프 없이 직선으로 되어있어서 목적지 도시는 정확히 하나뿐이다.

Example

#1
Input: paths = [["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]]
Output: "Sao Paulo"

#2
Input: paths = [["B", "C"], ["D", "B"], ["C", "A"]]
Output: "A"

#3
Input: paths = [["A", "Z"]]
Output: "Z"

Constraints

  • 1 <= paths.length <= 100
  • paths[i].length == 2
  • 1 <= cityAi.length, cityBi.length <= 10
  • cityAi != cityBi
  • 모든 문자열은 영어 소문자와 대문자, 공백으로 구성된다.

Solved

class Solution {
    public String destCity(List<List<String>> paths) {
        Set<String> cities = new HashSet<>();

        for(List<String> path : paths){
            cities.add(path.get(0));
        }

        for(List<String> path : paths){
            String dest = path.get(1);

            if(!cities.contains(dest)){
                return dest;
            }
        }

        return "";
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글