본문 바로가기

Algorithm/기타(기업등)

[EPPER/15회 5번]문자열 압축(하-1)

728x90
//프로그래머스에서는 main함수 및 입출력문이 필요하지 않습니다. 대신 solution함수만 작성하면 됩니다.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;


//숫자를 알파벳으로 변환하는 함수 
char convert(int count){
		
		if(count == 1) return 'A';
		else if(count == 2) return 'B';
		else if(count == 3) return 'C';
		else if(count == 4) return 'D';
		else if(count == 5) return 'E';
		else if(count == 6) return 'F';
		else if(count == 7) return 'G';
		else if(count == 8) return 'H';
		else if(count == 9) return 'I';
		else if(count == 10) return 'J';
		else if(count == 11) return 'K';
		else if(count == 12) return 'L';
		else if(count == 13) return 'M';
		else if(count == 14) return 'N';
		else if(count == 15) return 'O';
		else if(count == 16) return 'P';
		else if(count == 17) return 'Q';
		else if(count == 18) return 'R';
		else if(count == 19) return 'S';
		else if(count == 20) return 'T';
		else if(count == 21) return 'U';
		else if(count == 22) return 'V';
		else if(count == 23) return 'W';
		else if(count == 24) return 'X';
		else if(count == 25) return 'Y';
		else return 'Z';
		
		
	}
	
	
string answer;

string solution(string input){

		//이전 문자를 저장해둠 
		char preWord = input.at(0);
		char word;
		//여태까지 반복된 문자의 갯수 
		int count=1;
	
		//처음이 1로 시작하는경우 1을 정답에 부착하고 시작 
		if(input.at(0)=='1'){
			answer+="1";
		}
		
		//2번째 문자부터 끝까지 
		for(int i=1;i<input.size();i++){
			
			if(input.at(i)==preWord){ //이전문자와 현재 문자가 같은경우 
				count++;//반복 횟수를 1회 증가시킴
				
			}else{ // 이전 문자와 달라진 경우 
				word = convert(count);// 알파벳으로 변환후 
				answer+=word;//변환한 알파벳을 답에 부착 
				count=1;//횟수를 1로 초기화 
			}
			
			preWord = input.at(i); // 이전 문자를 현재문자로 갱신 
		}
		
		word = convert(count); //종료된 후 마지막 1회 더 진행해야함 
		answer+=word;
		return answer;
}


int main() {
	string input;

	cin >> input;

	cout<<solution(input);
	
	
	
	return 0;
}
728x90