Friday, September 19, 2014

LeetCode: Reverse Words in a String

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".


   void reverse(string &s, int i , int j)  
   {  
     while(i<j)  
     {  
       swap(s[i],s[j]);  
       i++;  
       j--;  
     }  
   }  
     
   
   void TrimWhiteSpace(string &s)  
   {  
     int n = s.length();  
     int i = 0, j = 0;  
     while(j<n && (s[j] == ' '))j++;  
   
     while(j < n)  
     {  
       while(j < n && (s[j] == ' '))j++;  
       while(j < n && s[j] != ' ')s[i++] = s[j++];  
       if(j<n){  
         s[i++] = s[j++];  
       }  
     }  
     if (i == 0)  
     {  
       s.clear();  
     }  
     else  
     {  
       if(s[i-1] == ' ')i--;  
       s = s.substr(0,i);  
     }  
   
   }  
   
   void reverseWords(string &s) {  
     TrimWhiteSpace(s);  
     int n = s.length();  
     reverse(s, 0 , n-1);  
     int i = 0;  
     while(i<n)  
     {  
       while(i<n && ((s[i] == ' ') ||(s[i] == '\t' )))i++;  
       if(i==n)break;  
       int j = i+1;  
       while(j<n && (s[j] != ' ') && (s[j] != '\t' ))j++;  
       j--;  
       reverse(s,i,j);  
       i = j+1;  
     }  
   }  

No comments:

Post a Comment