Official

B - A Reverse Editorial by en_translator


One may correctly output by properly implementing loops without modifying the received \(S\); but this time, we will introduce how to swap the \(l\)-th through \(r\)-th characters easily.
It can be achieved by the following steps.

  1. Let \(p=l\) and \(q=r\).
  2. Swap the \(p\)-th and \(q\)-th characters of the strings.
  3. Increment \(p\) by one and decrement \(q\) by one.
  4. Repeat 2. and 3. as long as \(p < q\).

Note that in many programming language the first character of a string is indexed as the \(0\)-th, not the \(1\)-st; this can be handled by decrementing \(l\) and \(r\) you received by \(1\) beforehand.

Sample code (C++):

#include<bits/stdc++.h>

using namespace std;

int main(){
  int l,r;
  string s;
  cin >> l >> r >> s;
  l--;r--;
  int p=l,q=r;
  while(p<q){
    swap(s[p],s[q]);
    p++;q--;
  }
  cout << s << '\n';
  return 0;
}

posted:
last update: