작성일 :

문제 링크

17413번 - 단어 뒤집기 2

설명

문자열에서 태그 안의 내용은 그대로 두고, 태그 밖에 있는 단어만 뒤집어 출력하는 문제입니다.


접근법

문자열을 앞에서부터 한 번만 순회합니다.

태그 밖에서 문자를 읽을 때는 현재 단어를 따로 모아 둡니다. 그러다가 공백이나 <를 만나면, 지금까지 모은 단어를 뒤집어서 출력하고 구분 문자도 함께 처리합니다.

태그 안으로 들어간 뒤에는 문자를 그대로 출력하면 됩니다. >를 만나면 다시 태그 밖으로 나옵니다.

즉, 태그 밖에서는 단어를 모았다가 뒤집어 내보내고, 태그 안에서는 그대로 출력하는 방식입니다.



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
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Text;

class Program {
  static void FlushWord(StringBuilder word, StringBuilder result) {
    for (int i = word.Length - 1; i >= 0; i--)
      result.Append(word[i]);
    word.Clear();
  }

  static void Main() {
    string s = Console.ReadLine()!;
    var word = new StringBuilder();
    var result = new StringBuilder();
    bool inTag = false;

    foreach (char ch in s) {
      if (ch == '<') {
        FlushWord(word, result);
        inTag = true;
        result.Append(ch);
      } else if (ch == '>') {
        inTag = false;
        result.Append(ch);
      } else if (inTag) {
        result.Append(ch);
      } else if (ch == ' ') {
        FlushWord(word, result);
        result.Append(ch);
      } else {
        word.Append(ch);
      }
    }

    FlushWord(word, result);
    Console.WriteLine(result.ToString());
  }
}

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <bits/stdc++.h>
using namespace std;

void flush_word(string& word, string& result) {
  for (int i = (int)word.size() - 1; i >= 0; i--)
    result.push_back(word[i]);
  word.clear();
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  string s;
  getline(cin, s);

  string word, result;
  bool in_tag = false;

  for (char ch : s) {
    if (ch == '<') {
      flush_word(word, result);
      in_tag = true;
      result.push_back(ch);
    } else if (ch == '>') {
      in_tag = false;
      result.push_back(ch);
    } else if (in_tag) {
      result.push_back(ch);
    } else if (ch == ' ') {
      flush_word(word, result);
      result.push_back(ch);
    } else {
      word.push_back(ch);
    }
  }

  flush_word(word, result);
  cout << result << "\n";

  return 0;
}

Tags: 17413, BOJ, C#, C++, 구현, 문자열, 백준, 알고리즘

Categories: ,