문자열 뒤집기

Subin·2024년 8월 1일

Algorithm

목록 보기
14/69

[내 풀이]

#include <string>
#include <algorithm>  // 이거 추가 안 할거면, 반복문 사용해서 뒤에서부터 하나씩 저장
#include <vector>

using namespace std;

string solution(string my_string, int s, int e) {
    string answer = "";
    string rev = "";

    // 뒤집을 문자열
    rev = my_string.substr(s, e-s+1);
    // 뒤집기
    reverse(rev.begin(), rev.end());
    // result에 안 뒤집은 거 + 뒤집은 거 더하기
    answer = my_string.substr(0, s) + rev + my_string.substr(e+1);

    return answer;
}

[다른 사람 풀이1] - reverse 사용

#include <string>
#include <vector>
#include <algorithm>
using namespace std;

string solution(string my_string, int s, int e) {
    reverse(my_string.begin()+s,my_string.begin()+e+1);
    return my_string;
}

[다른 사람 풀이1] - swap 사용

#include <string>
#include <vector>

using namespace std;

string solution(string my_string, int s, int e) {
    string answer = "";
    for (int i = 0; i <= (e - s) / 2; i++)
        swap(my_string[s + i], my_string[e - i]);
    return my_string;
}

reverse(str.begin(), str.end());

참고 블로그
https://portable-paper.tistory.com/entry/%EB%AC%B8%EC%9E%90%EC%97%B4-%EB%92%A4%EC%A7%91%EA%B8%B0-C

profile
성장하며 꿈꾸는 삶을 살아가고 있는 대학생입니다😊

0개의 댓글