Post

[Programmers] #12919 - 서울에서 김서방 찾기 [Java][C++][Python]

[Programmers] #12919 - 서울에서 김서방 찾기 [Java][C++][Python]

문제 링크


1. 아이디어

배열에서 "Kim"의 위치를 찾아 문장에 끼워 넣는 문제로, "Kim"은 정확히 한 번만 나오므로 처음 일치하는 원소의 위치가 곧 답이다. 위치는 0부터 센 인덱스이고(예시에서 ["Jane", "Kim"]의 답이 1이다) 문장에도 그대로 들어가므로 별도 보정이 필요 없다.


2. 코드

풀이 [Java][C++][Python]

1
2
3
4
5
6
7
import java.util.*;

class Solution {
    public String solution(String[] seoul) {
        return "김서방은 " + List.of(seoul).indexOf("Kim") + "에 있다";
    }
}

배열에는 indexOf가 없어 List.of로 감싼 뒤 indexOf로 위치를 찾았다.

1
2
3
4
5
6
#include <bits/stdc++.h>
using namespace std;

string solution(vector<string> seoul) {
    return "김서방은 " + to_string(find(seoul.begin(), seoul.end(), "Kim") - seoul.begin()) + "에 있다";
}

std::find는 이터레이터를 반환하므로 seoul.begin()을 빼서 인덱스로 바꿨다.

1
2
def solution(seoul):
    return "김서방은 " + str(seoul.index("Kim")) + "에 있다"

This post is licensed under CC BY 4.0 by the author.