Thursday, August 27, 2015

Leetcode: Reverse Words in a String (8ms) (string)(two pointers)

PROBLEM:


https://leetcode.com/problems/reverse-words-in-a-string/


---------------------------------

Searching a word from right to left, using two pointers to mark the location of a word. using another string to temporally store the result.


/////////////////////////////////////////////////
//8ms
class Solution {
public:
       void reverseWords(string &s) {
              int n = s.size(), l = n - 1, r = n - 1;
              string res;
              while (l>-1){
                     int i = l;
                     //looking for non-space char
                     while (i>-1 && s[i] == ' ')i--;
                     r = i;
                     if (i == -1)break;//all leading char are ' '.
                     //looking for space. Note: put i>-1 ahead of s[i]!=' ';
                     while (i>-1 && s[i] != ' ')i--;
                     l = i + 1;
                     res.append(s, l, r - l + 1);
                     res.push_back(' ');
                     l = i - 1;
                     r = l;
              }
              //check input and check tmp result and remove final space
              if(n!=0 && res.size()!=0)res.erase(res.size()-1,1);
              s = res;
       }

};

No comments:

Post a Comment