반응형

대단한 알고리즘은 아니지만, 라이브러리로 하나 정도 만들어둘만한 방법을 한번 만들어보고자 한다.


문자열 뒤집기를 다음과 같이 하는 프로그램을 만들어 보려 한다.


ex ) I Love You 라는 문자열이 주어지면 You Love I 라는 문자열로 변환시키는 프로그램이다.


즉, 문자열을 뒤집되, 단어는 유지해야 하는 프로그램이다.



다른 예를 들어보자


1. A little boy is in the forest -> forest the in is bot little A 

2. ABC -> ABC

3. Crocus Homepage -> Homepage Crocus


바로 코드를 본 후 분석을 해보자.


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
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
 
using namespace std;
 
int main()
{
    string str;
    getline(cin, str);
 
    reverse(str.begin(), str.end());
    str += ' ';
 
    int len = str.size();
 
    int start = 0;
    for (int end = 0; end < len; end++)
        if (str[end] == ' ')
        {
            reverse(str.begin() + start, str.begin() + end);
            start = end + 1;
        }
 
    cout << str << endl;
 
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus



우선 getline로 개행을 제외한 모든 input을 받아들인다.(cin으로 하면 공백 ' '을 받을 수 없다.)


그리고 reverse를 통해 str을 뒤집고 난 후, 가장 마지막에 ' '를 추가해준다. 이 의미는 hello world -> world hello -> world hello   로 공백을 만들겠다는 의미이다.


저 붉은 공백을 만든 이유는 아래 for문에 있다.


아래 for문은 공백을 만나면 시작점 - 공백을 만나기 전까지의 string을 뒤집어준다.


즉, hello world가 reverse에 의해 dlrow olleh 가 되어있다면 world olleh로 변경시켜주는 역할이다.


이 과정을 위해 가장 마지막에도 공백이 필요했던 것이고


결국 world hello로 변환시킬 수 있다는 것이다.












반응형