53. Reverse Words in a String

class Solution { public: /* * @param s: A string * @return: A string */ string reverseWords(string &s) { // write your code here std::vector<string> strs; const int size = s.size(); if(size == 0){ return s; } int i = 0; while(i < size){ while(i < size && s[i] == ' '){ i++; } if(i == size){ break; } int start = i; while(i < size && s[i] != ' '){ i++; } strs.push_back(s.substr(start, i - start)); } string res = ""; if(strs.size() == 0){ return res; } for(int i = strs.size() - 1; i >= 1; i--){ res += strs[i] + ' '; } res += strs[0]; return res; } };

Comments

Popular posts from this blog

算法的比较