Header Ad

HackerEarth Nobita and String problem solution

In this HackerEarth Nobita and String problem solution Doraemon gave Nobita a gadget that swaps words inside a string in the following manner :

If there are W words, word 1 is swapped with word W, word 2 is swapped with word W-1 and so on. The problem is that Nobita himself cannot verify the answer for large strings. Help him write a program to do so.


HackerEarth Nobita and String problem solution


HackerEarth Nobita and String problem solution.

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


int main()
{
int t;
cin>>t;
getchar();
while(t--)
{ string s;
getline(cin,s);
reverse(s.begin(),s.end());

string :: iterator it,it1;
for(it = s.begin();it!=s.end(); it++)
{
it1=it;
while(it!=s.end() && *it!=' ')
it++;

reverse(it1,it);
if(*it == '\n' || it == s.end())
break;
}

cout<<s<<endl;
}
return 0;
}

Second solution

#include <cstdlib>
#include <stdio.h>
#include <cstring>
#include <complex>
#include <vector>
#include <cmath>
#include <ctime>
#include <iostream>
#include <numeric>
#include <algorithm>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <iomanip>
#include <utility>
#include <locale>
#include <sstream>
#include <string> // this should be already included in <sstream>

using namespace std;

//short lazieeeeeee
#define FOR(i,n) for(i=0;i<n;i++)
#define FORI(i,a,n) for(i=a;i<n;i++)
#define FORC(it,C) for(it=C.begin();it!=C.end();it++)
#define scanI(x) scanf("%d",&x)
#define scanD(x) scanf("%lf",&x)
#define print(x) printf("%d\n",x)
#define ll long long
#define number32 4294967296ull
#define MAX 100001
#define len(s) s.length()
#define ff first
#define ss second

using namespace std;

//containers
typedef map<int,int> Mii;
typedef map<char,int> Mci;
typedef pair<int,int> Pii;
typedef vector<int> vi;
typedef vector<int> vc;
typedef vector<ll> vl;

//iterators
typedef map<int,int>::iterator Miii;
typedef map<char,int>::iterator Mcii;

int main()
{
int t;
cin>>t;
getchar();
int i;
string s;
while(t--)
{
getline(cin,s);
// cout<<s<<endl;
//char s[100001];
//cin.getline(s,100000);
string temp;
vector <string> cds;
stringstream ss (s);
while(ss >> temp)
cds.push_back(temp);
reverse(cds.begin(),cds.end());
for(i=0;i<cds.size();i++)
{
cout<<cds[i]<<" ";
}
cout<<endl;
//* */
}
return 0;
}

Post a Comment

0 Comments