[백준 17011] Cold Compress (C#, C++) - soo:bak
작성일 :
문제 링크
설명
문자열을 연속 구간으로 나누어 길이와 문자를 순서대로 출력하는 문제입니다.
접근법
문자를 왼쪽부터 보면서 같은 문자가 이어지는 길이를 세고, 구간이 끝날 때마다 개수와 문자를 출력합니다.
다음 문자가 바뀌면 새 구간을 시작합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
using System.Text;
class Program {
static void Main() {
var t = int.Parse(Console.ReadLine()!);
var sb = new StringBuilder();
for (var i = 0; i < t; i++) {
var line = Console.ReadLine()!;
var cnt = 1;
for (var j = 1; j <= line.Length; j++) {
if (j < line.Length && line[j] == line[j - 1]) cnt++;
else {
sb.Append(cnt).Append(' ').Append(line[j - 1]);
if (j < line.Length) sb.Append(' ');
cnt = 1;
}
}
sb.AppendLine();
}
Console.Write(sb);
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int t; cin >> t;
string line;
for (int i = 0; i < t; i++) {
cin >> line;
int cnt = 1;
for (int j = 1; j <= (int)line.size(); j++) {
if (j < (int)line.size() && line[j] == line[j - 1]) cnt++;
else {
cout << cnt << ' ' << line[j - 1];
if (j < (int)line.size()) cout << ' ';
cnt = 1;
}
}
cout << "\n";
}
return 0;
}