亚麻的OA题
reverse words(leetcode有),要求尽可能time/space efficient
1,input的string的前后空格都要去除
2,若是input string 中的俩个word 之间有多个空格, 则仅需要保留一个。
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.
class Solution { public: void reverseWords(string &s) { if (s.empty()) return ; if ( s.size () == 1 && s !=" ") return ; // only one char //cout <<" the size of the input string is large than 1"<< endl; int st =0; int ed = s.size ()-1; int size = s.size(); string s2; while ( st < size && s[st] == ‘ ‘) st++; if ( st == size ) { s=""; return ;} while ( ed >0 && s[ed] == ‘ ‘) ed--; int p1 = ed; int p2 = p1; cout << " all the sapce is removed, and size is , "<< size << " st is "<< st<<" end is " << ed<<endl; while ( p1 >= st ){ if (s[p1] == ‘ ‘){ p1--; continue ;} p2 = p1; while ( p2 >= st ){ // cout <<"p2 is " << p2 << " p1 is " << p1 <<endl; if ( p2 == st) {//the last char. // cout <<" the last char"<< endl; s2 += s.substr(p2, p1 -p2 +1); s = s2; return ; } if ( s[p2] != ‘ ‘) p2 --; else{ s2 += s.substr(p2+1, p1-p2); // cout << " copy the word "<< s.substr(p2+1, p1-p2) <<" from "<< p2 << " to "<< p1<< endl;; s2 += ‘ ‘; p1 = p2; break; } } } //s = s2; return ; } };