[백준 15904] UCPC는 무엇의 약자일까? (C#, C++) - soo:bak
작성일 :
문제 링크
설명
문자열에서 일부 문자를 지워 대소문자를 유지한 채 UCPC를 순서대로 만들 수 있는지 확인하는 문제입니다.
접근법
목표 문자열 UCPC를 두고 입력을 왼쪽부터 보면서 일치하는 문자를 찾을 때마다 목표 인덱스를 하나씩 증가시킵니다. 끝까지 보았을 때 목표 인덱스가 4라면 만들 수 있으므로 I love UCPC, 아니면 I hate UCPC를 출력하면 됩니다.
시간 복잡도는 O(N)입니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
class Program {
static void Main() {
var s = Console.ReadLine()!;
var target = "UCPC";
var idx = 0;
foreach (var ch in s) {
if (idx < 4 && ch == target[idx])
idx++;
}
Console.WriteLine(idx == 4 ? "I love UCPC" : "I hate UCPC");
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
getline(cin, s);
string target = "UCPC";
int idx = 0;
for (char ch : s) {
if (idx < 4 && ch == target[idx])
idx++;
}
cout << (idx == 4 ? "I love UCPC" : "I hate UCPC") << "\n";
return 0;
}