Advertisement
jcvitanovic

Zad14

Dec 19th, 2014
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. /*
  2. 19.12.2014
  3. Problem 14 Describe an algorithm for reversing the words in a string; for example ”My
  4. name is Amit Agarwal” becomes ”Agarwal Amit is name My”. An O(n) and in-place
  5. solution is appreciable.
  6. */
  7.  
  8. #include<stdio.h>
  9. #include<string>
  10. #include<iostream>
  11.  
  12. using namespace std;
  13.  
  14. void reverseChunk(char *s, int start, int end){
  15.     while (start < end){
  16.         char tmp = s[start];
  17.         s[start] = s[end];
  18.         s[end] = tmp;
  19.         start++;
  20.         end--;
  21.     }
  22. }
  23.  
  24. void reverse(string s){
  25.     int len = s.length();
  26.     reverseChunk(&s[0], 0,  len - 1);
  27.     cout << s << "\n";
  28.     int start = 0;
  29.     int end = 0;
  30.     while (start < len){
  31.         while (end < len && s[end] != ' ')
  32.             end++;
  33.         reverseChunk(&s[0], start, end-1);
  34.         start = end + 1;
  35.         end = start;
  36.     }
  37.     cout << s << "\n";
  38.    
  39.  
  40. }
  41.  
  42. int main(){
  43.     string s;
  44.     getline (cin, s);
  45.     reverse(s);
  46.  
  47.     return 0;
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement