๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์˜์–ด ๋๋ง์ž‡๊ธฐ(Level 2)

by dkswnkk 2022. 3. 4.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์˜์–ด ๋๋ง์ž‡๊ธฐ

3 ["tank", "kick", "know", "wheel", "land", "dream", "mother", "robot", "tank"] [3,3] 5 ["hello", "observe", "effect", "take", "either", "recognize", "encourage", "ensure", "establish", "hang", "gather", "refer", "reference", "estimate", "executive"] [0,0]

programmers.co.kr

 

์ฝ”๋“œ

#include <string>
#include <vector>
#include <map>
#include <iostream>

using namespace std;


vector<int> solution(int n, vector<string> words) {
    vector<int> answer;
    map<string,int> duplicate;
    int cycle = 1;
    char before_char = words[0].back();
    duplicate[words[0]]++;

    for(int i=1; i<words.size(); i++){
        if(i%n==0) cycle++;

        if(words[i].front()!=before_char){
            answer.push_back((i%n)+1);
            answer.push_back(cycle);
            return answer;
        }

        if(duplicate[words[i]]!=0){
            answer.push_back((i%n)+1);
            answer.push_back(cycle);
            return answer;
        }
        before_char = words[i].back();
        duplicate[words[i]]++;

    }

    if(answer.size()==0){
        answer.push_back(0);
        answer.push_back(0);
    }

    return answer;
}

 

ํ’€์ด

๋ฌธ์ œ๋ฅผ ๋จผ์ € ์„ค๋ช…ํ•˜์ž๋ฉด n๋ช…์˜ ์‚ฌ๋žŒ์ด ์˜๋‹จ์–ด๋กœ ๋๋ง์ž‡๊ธฐ๋ฅผ ์ง„ํ–‰ํ•˜๋Š”๋ฐ ๋๋ง์„ ์ด์–ด๊ฐ€์ง€ ๋ชปํ•˜๊ฑฐ๋‚˜ ์ด์ „์— ์‚ฌ์šฉํ–ˆ๋˜ ๋‹จ์–ด๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋๋‚˜๊ฒŒ ๋˜๊ณ  ๊ทธ๋•Œ ํ‹€๋ฆฐ ์‚ฌ๋žŒ์˜ ๋ฒˆํ˜ธ์™€ ๋ช‡ ๋ฒˆ์งธ ์‚ฌ์ดํด ๋•Œ ํ‹€๋ ธ๋Š”์ง€ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‹จ์ˆœํ•˜๊ฒŒ O(N)์‹œ๊ฐ„ ๋ณต์žก๋„๋กœ ์ด๋ฒˆ ๋‹จ์–ด์˜ ์ฒซ ๊ธ€์ž๊ฐ€ ์ด์ „ ๋‹จ์–ด์˜ ๋ ๊ธ€์ž์™€ ๋งž๋Š”์ง€ ์กฐ๊ฑด๋ฌธ์œผ๋กœ ํŒ๋ณ„ํ•˜์˜€๊ณ , Map ํ…Œ์ด๋ธ”์„ ์‚ฌ์šฉํ•˜์—ฌ ์ค‘๋ณต ํŒ๋‹จ์„ ํ•˜์—ฌ ํ•ด๋‹น ์กฐ๊ฑด์— ๊ฑธ๋ฆด ๊ฒฝ์šฐ ๋๋ง์ž‡๊ธฐ๊ฐ€ ๋๋‚œ ๊ฒฝ์šฐ์ด๊ธฐ ๋•Œ๋ฌธ์— answer ๋ฒกํ„ฐ์— ์ถ”๊ฐ€ํ•˜๊ณ  return ํ–ˆ์Šต๋‹ˆ๋‹ค. answer ๋ฒกํ„ฐ์˜ ์‚ฌ์ด์ฆˆ๊ฐ€ 0 ์ธ ๊ฒฝ์šฐ๋Š” ์ „๋ถ€ ๋‹ค ์˜ฌ๋ฐ”๋ฅด๊ฒŒ ๋๋ง์ž‡๊ธฐ๋ฅผ ์ง„ํ–‰ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์— ์•„๋ฌด๊ฒƒ๋„ ๋“ค์–ด์žˆ์ง€ ์•Š๋Š” ์ƒํƒœ์ด๊ธฐ์— 0์„ ์ง์ ‘ ์‚ฝ์ž…ํ•ด์ฃผ์–ด ์ถœ๋ ฅํ–ˆ์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€