728x90

영어 끝말잇기

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 설명

N 명의 사람이 주어진 단어들을 하나씩 말하면서 끝말잇기가 맞는지, 같은 단어를 사용했는지 확인하는 문제다.

문제 풀이

소스코드 : C++

  1. 중복되는 단어가 불러졌는지 확인하기 위한 unordered_set 선언
  2. 영어 단어를 몇 개를 말했는지 세는 cnt 선언
  3. words.size()N개씩 잘라가며 idx를 갱신해주기위한 idx = i%n
  4. 이전 단어의 끝부분과 현재 단어의 앞부분을 비교해서 다르다면 종료 시점의 사람 idx와 말한 갯수를 answer에 푸시하고 반환
  5. set안에 존재하지 않는 단어라면 set 넣고 해당 사람 인덱스를 증가시킨다
  6. 이미 존재하는 단어라면 4번과 같은 행동 후 종료
#include <string>
#include <vector>
#include <iostream>
#include <unordered_set>

using namespace std;

vector<int> solution(int n, vector<string> words) {
    vector<int> answer;
    unordered_set<string> us;
    vector<int> cnt(n,0);
    for(int i=0; i<words.size(); i++){ 
        int idx = i%n;
        string key = words[i];
        if(i>0 && words[i-1].back() != words[i].front()){
            answer.push_back(idx+1);
            answer.push_back(cnt[idx]+1);
            return answer;
        }
        if(!us.count(key)){
            us.insert(key);
            cnt[idx]++;
        }
        else{
            answer.push_back(idx+1);
            answer.push_back(cnt[idx]+1);
            return answer;
        }
    }

    return answer = {0,0};
}
int main(){
    vector<string> w = {"tank", "kick", "know", "wheel", "land", "dream", "mother", "robot","tank"};
    for(auto ans : solution(3,w))
        cout<<ans<<" ";
    return 0;
}

소스코드 : Python

2번째 단어부터 반복하며 이전 단어와 현재 단어를 비교하고 현재 단어가 이전 단어들 중에 있는지 확인하여 조건에 맞지 않는다면 [(i%n)+1, (i//n)+1] 을 반환한다.

슬라이싱이 참 유용한 파이썬!

def solution(n, words):
    for i in range(1, len(words)):
        if words[i-1][-1] != words[i][0] or words[i] in words[:i]: return [(i%n)+1, (i//n)+1]
    else: return [0,0]
728x90
300x250
WONILLISM