Lv 0. 문자열 뒤집기

https://school.programmers.co.kr/learn/courses/30/lessons/120822

 

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

string solution(string s) {
    reverse(s.begin(),s.end());    
    return s;
}

<algorithm> 헤더에 있는 reverse() 함수를 사용하였다. 

 

다른 사람의 풀이를 보다보니 첨부해보면 좋을만한 풀이들이 눈에 보여서 같이 첨부해본다. 

#include <bits/stdc++.h>

using namespace std;

string solution(string my_string) {
    return string(my_string.rbegin(), my_string.rend());
}

 

각각의 char를 string answer에 더해가는 이 풀이또한 재미있는 풀이같다. 

알아두면 직관적이고 string 헤더에 있는 string 함수나 algorithm 헤더에 있는 reverse() 함수가 기억이 안날때 이용할 수 있을것 같다. 

#include <string>
#include <vector>
using namespace std;
string solution(string my_string) {
    string answer = "";
    for(int i = my_string.size() - 1; i >= 0; i--)
        answer += my_string[i];
    return answer;
}
  Comments,     Trackbacks