Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 19.12.2014
- Problem 14 Describe an algorithm for reversing the words in a string; for example ”My
- name is Amit Agarwal” becomes ”Agarwal Amit is name My”. An O(n) and in-place
- solution is appreciable.
- */
- #include<stdio.h>
- #include<string>
- #include<iostream>
- using namespace std;
- void reverseChunk(char *s, int start, int end){
- while (start < end){
- char tmp = s[start];
- s[start] = s[end];
- s[end] = tmp;
- start++;
- end--;
- }
- }
- void reverse(string s){
- int len = s.length();
- reverseChunk(&s[0], 0, len - 1);
- cout << s << "\n";
- int start = 0;
- int end = 0;
- while (start < len){
- while (end < len && s[end] != ' ')
- end++;
- reverseChunk(&s[0], start, end-1);
- start = end + 1;
- end = start;
- }
- cout << s << "\n";
- }
- int main(){
- string s;
- getline (cin, s);
- reverse(s);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement