본문 바로가기

🖥️ 오늘의 백준

백준 2941번 : 크로아티아 [C++, Python]

https://www.acmicpc.net/problem/2941

 

2941번: 크로아티아 알파벳

예전에는 운영체제에서 크로아티아 알파벳을 입력할 수가 없었다. 따라서, 다음과 같이 크로아티아 알파벳을 변경해서 입력했다. 크로아티아 알파벳 변경 č c= ć c- dž dz= đ d- lj lj nj nj š s= ž z=

www.acmicpc.net

전체코드 : C++ ver.

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

int main() {
	vector<string> croatia = { "c=", "c-", "dz=", "d-", "lj", "nj","s=", "z=" };
	string input;
	cin >> input;

	for (int i = 0; i < croatia.size(); i++) {
		int s = input.find(croatia[i]);
		while (input.find(croatia[i]) != string::npos) {
			input.replace(s, croatia[i].length(), "*");
            s = input.find(croatia[i], s+1);
		}
	}
	
	cout << input.length();
}

배열로 크로아티아 알파벳을 지정해도 됨 string croatia = {~~~};

string::npos find함수에서 값이 없으면 인덱스 반환을 안함. 이때, 없는 문자열을 찾으라고하면 string::npos를 반환함

즉,

while (input.find(croatia[i]) != string::npos) { //문자열이 발견된다면
			input.replace(s, croatia[i].length(), "*"); //해당 인덱스에서 크로아티아 알파벳 길이만큼 *로 바꾸겠다
            s = input.find(croatia[i], s+1); // s+1 인덱스부터 다시 find
		}

find() #include <string>

문법 : find(”찾고싶은 문자열”, 찾기 시작할 인덱스);

while문을 쓴 이유: 같은 크로아티아알파벳이 여러개 있을 수도 있으니 모두 다 찾을 때까지 반복

 

 

전체코드 : Python ver.

croatia = ['c=', 'c-', 'dz=', 'd-', 'lj', 'nj', 's=', 'z=']

N = input()

for i in croatia :
    N = N.replace(i, '*')

print(len(N))

input으로 입력받은 값에서 크로아티아 배열에 해당하는 값을 찾고 값이 있다면 (*)문자로 대체해준다.

이후 문자열의 길이를 출력하면 된다.