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.
Example:
Input: s = "hello world"
Output: world hello
Approach
C++
#include <bits/stdc++.h>using namespace std;string nobitaAndString(string s){vector<string> res;int i = 0, l = 0;string x = "";string ans = "";while (i < s.size()){while (i < s.size() && s[i] != ' '){x += s[i];i++;}i++;res.push_back(x);x = "";}for (int j = res.size() - 1; j >= 0; j--){ans += res[j];ans += ' ';}return ans;}int main(){string s = "hello world";cout << nobitaAndString(s) << "\n";return 0;}
No comments:
Post a Comment