[프로그래머스] 단어 변환 (C++)

2021. 2. 18. 22:23·코딩 테스트
728x90

🔮문제

begin -> target 단어로 가는 가장 짧은 단계 return

 

1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다.

2. words에 있는 단어로만 변환할 수 있습니다.

 

🔮풀이

1. target이 words에 존재하는 경우

2. target이 words에 존재하지 않는 경우

  2-1. begin과 target의 차이=1 이면 탐색 종료

  2-2. begin과 target의 차이=1이 아니면 차이가 1인 다음 단어 탐색, 단계(cnt) + 1


🔮코드

#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int solution(string begin, string target, vector<string> words) {
    int answer = 999;
    int cnt = 0;
    bool isOk = false;
    
    //1. target이 words배열에 존재하는지 확인, 없으면 0 return
    for(auto x : words){
        if(x == target)
            isOk = true;
    }
    
    if(isOk == false)
        return 0;
    
    //2. target이 words배열에 존재 할 경우
    for(int i=0; i<words.size(); i++){
        string cur = words[i];
        int tmp_cnt = 0;
        //2-1. 현재 단어와 target단어의 차이가  1이면 탐색 종료
        for(int j=0; j<target.size(); j++){
            if(begin[j] != target[j])
                tmp_cnt++;
        }
        if(tmp_cnt == 1){
            cnt+=1;
            break;
        }
        else
            tmp_cnt = 0;
        //2-2. 그렇지 않을 경우 현재와 차이가 1인 다음 단어 탐색
        for(int j = 0; j<cur.size(); j++){
            if(begin[j] != cur[j])
                tmp_cnt++;
        }
        if(tmp_cnt == 1){
            begin = words[i];
            cnt += 1;
        }
    }
    answer = min(answer, cnt);
    return answer;
}
728x90

'코딩 테스트' 카테고리의 다른 글

[Codility] Lesson3. FrogJmp (C++)  (0) 2021.02.23
[Codility] Lesson1. BinaryGap (C++)  (0) 2021.02.23
[Codility] Lesson2. CyclicRotation (C++)  (0) 2021.02.22
[Codility] Lesson2. OddOccurrencesInArray (C++)  (0) 2021.02.22
[프로그래머스] 가장 먼 노드 (C++)  (0) 2021.02.18
'코딩 테스트' 카테고리의 다른 글
  • [Codility] Lesson1. BinaryGap (C++)
  • [Codility] Lesson2. CyclicRotation (C++)
  • [Codility] Lesson2. OddOccurrencesInArray (C++)
  • [프로그래머스] 가장 먼 노드 (C++)
zoodi
zoodi
IT/개발 관련 지식을 기록하는 블로그입니다.
  • zoodi
    오늘의 기록
    zoodi
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 후기
        • 컨퍼런스
        • 일상리뷰
      • 금융경제
        • 뉴스
        • 금융IT용어
        • 경제 및 부동산
      • 코딩 테스트
      • 스터디
        • JAVA
        • Kotlin
        • Spring
        • React, Nextjs
        • 인공지능 AI
        • Cloud & k8s
        • Kafka
        • Database
        • Network
        • Algorithm
        • Hadoop
        • LINUX
        • R Programming
        • 기타 (소공, 보안)
      • 도서
      • 기타
  • 블로그 메뉴

    • 홈
    • 스터디
    • 금융경제
    • 후기
    • 기타
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    알고리즘
    프로그래머스
    CodingTest
    C++
    Spring
    LeetCode
    금융용어
    네트워크
    코테
    Kotlin
    자바
    스프링부트
    자료구조
    쿠버네티스
    코딩
    codility
    카카오코테
    코딩테스트
    MySQL
    db
    스프링
    java
    코딜리티
    이분탐색
    pythoncodingtest
    코테공부
    리트코드
    springboot
    Python
    kafka
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
zoodi
[프로그래머스] 단어 변환 (C++)
상단으로

티스토리툴바