Swapping Characters

You are given a string of length N. You have to follow some rounds of swapping in the string until the below explained condition is reached.

In each round, you have to swap the ith and (i+1)th character, then (i+2)th and (i+3)th character, and continue till the end of the string. In each round, a character from the left will be locked i.e not available for swapping after this round, thus after some rounds of swapping, all the characters will be locked at their final position to stop any more rounds of swapping.

Example:

Input:  n = 6, s = "abcdef"
Output: bdfeca

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string swappingCharacters(int nstring s)
{
    int j = 0;
    string res = ""temp = "";
    for (int i = 0i < ni++)
    {
        if (i & 1)
            res += s[i];
        else
            temp += s[i];
    }
    for (int i = temp.size() - 1i >= 0i--)
        res += temp[i];
    return res;
}
int main()
{

    int n = 6;

    string s = "abcdef";

    cout << swappingCharacters(ns<< "\n";

    return 0;
}


No comments:

Post a Comment