알고리즘 공부/백준
17413 단어 뒤집기 2 with C++
당장하자
2022. 7. 7. 15:16
문제
https://www.acmicpc.net/problem/17413
17413번: 단어 뒤집기 2
문자열 S가 주어졌을 때, 이 문자열에서 단어만 뒤집으려고 한다. 먼저, 문자열 S는 아래와과 같은 규칙을 지킨다. 알파벳 소문자('a'-'z'), 숫자('0'-'9'), 공백(' '), 특수 문자('<', '>')로만 이루어져
www.acmicpc.net
해결한 방법
string 코드
1. string 변수에 getline으로 한 줄입력을 받습니다.
2. string의 각 철자를 인덱스로 접근해서 <를 만나면 state를 1로 정의해서 state가 1일때 for문의 나머지 코드를 건너뛰고 for문을 다시 실행시킵니다.
3. front_pos를 단어의 시작 back_pos을 단어의 끝으로 설정해서 단어를 찾아냅니다.
(reverse함수의 특징때문에 back_pos는 단어끝 다음 인덱스입니다.)
3, state가 1이 아니고 '<'또는 ' '(공백)또는 문장의 끝을 만나면 이전까지의 단어를 reverse함수로 뒤집어 줍니다.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
string input;
getline(cin, input);
int state = 0;
int front_idx = 0, back_idx = 0;
for (int i = 0; i < input.size(); i++){
if (input[i] == '<') {
if (front_idx != back_idx) {
reverse(input.begin() + front_idx, input.begin() + back_idx);
}
state = 1;
continue;
}
if (input[i] == '>') {
state = 0;
front_idx = back_idx = i + 1;
continue;
}
if (state) {
continue;
}
if (input[i] == ' ') {
if (front_idx != back_idx) {
reverse(input.begin() + front_idx, input.begin() + back_idx);
}
front_idx = back_idx = i + 1;
}
else {
back_idx++;
}
}
if (front_idx != back_idx) {
reverse(input.begin() + front_idx, input.begin() + back_idx);
}
cout << input << "\n";
return 0;
}
배열 코드
#include <iostream>
#include <string>
#include <algorithm>
#define MAX 100001
using namespace std;
void _switch(char* str, int front, int back) {
char temp;
while (back > front) {
temp = str[back];
str[back] = str[front];
str[front] = temp;
front++; back--;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL); std::cout.tie(NULL);
char* input = new char[MAX];
cin.getline(input, MAX);
int state = 0;
int front_idx = 0, back_idx = 0;
for (int i = 0; i < MAX; i++){
if (input[i] == '<') {
state = 1;
if (front_idx < back_idx) {
_switch(input, front_idx, back_idx-1);
}
}
else if (input[i] == '>') {
state = 0;
front_idx = back_idx = i + 1;
}
else if (!state && (input[i] == ' ' || input[i] == '\0')) {
if (front_idx < back_idx) {
_switch(input, front_idx, back_idx-1);
}
front_idx = back_idx = i + 1;
}
else {
back_idx++;
}
if (input[i] == '\0')
break;
}
std::cout << input << "\n";
delete[] input;
return 0;
}