Wednesday, November 26, 2014

Reverse Words in a String -- Leetcode

Question:
Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
Answer:
class Solution {
public:
    void reverseWords(string &s) {
        string ss;
        string res;
        
        for(int i=0; s[i]!='\0';++i){
            if(s[i]!=' '){
               ss.append(s[i],1);
            }
                 //For invalid ' ', if there exists duplicate ' '.
            else if(s[i] == ' ' && s[i+1] == ' '){
                continue;
            }
                 //For effective ' ', if there exists duplicate ' '. For case: "aa bb   cc   ".
            else if(s[i] == ' ' && s[i+1] != ' ' && s[i+1] != '\0'){
                res.insert(0," ");
                res.insert(1,ss);
                ss.clear();
            }
                 //For last word.
            else if(s[i] == ' ' && s[i+1] == '\0'){
                res.insert(0,ss);
                ss.clear();
            }
        }
        s = res;
    }
};

No comments:

Post a Comment