亚麻:2018-3 reverse words
亚麻的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.
solution 1 :
use slide window to mark every word
skip all the spaces at the tail of the string.
if it is not the last one, " " + word + res;
else word + res
then s =res
class Solution { public: //use slide window to reverse each word in string s. void reverseWords(string &s) { if ( s.size() ==0 ){ s = {""}; return ;}// s is a empty string. int sp =0; int ep =s.size()-1; while ( s[ep]==' ') { ep--; continue;} if( ep < 0) {s= {""}; return ;}// all chars in string is space. int end = ep; string res; while ( ep <= end ){ while ( s[sp] ==' ') { sp++; continue ;} ep = sp; while( s[ep] !=' '&& ep!= end){ ep++; continue;} if (ep != end) { res = " " +s.substr(sp, ep-sp) + res; cout << " sapce is appended" << endl; } else { res = s.substr(sp, ep-sp+1) + res; cout <<" no apace "<< endl; break; } //arrive the last word. sp = ep; } s = res; } };
solution 2:
1 first reverse input string.
2 skip the sapce at the tail of the string and set 'end' at the last un-space character. .
3 find word one by one , and for any word
-- reverse the word and copy it to the res.
-- if the word is not the last one, append one ' ' in res. else do not append.
class Solution { public: //reverse a string. void _reverseWord(string&s , int sp , int ep){ do { if ( sp == ep || sp > ep ) break; char temp = s[ep]; s[ep] = s[sp]; s[sp] = temp; sp++; ep--; }while (true); } void reverseWords(string &s) { int sp = 0; int ep = s.size( ) -1; if ( s.empty() ) return; if (s.size() == 1 ){ if ( s[0] == ' ') s = {""}; return ; } // reverse the original string. _reverseWord(s, sp, ep); // skip all the right space in string. while ( s[ep]==' '){ ep--; continue;} int end = ep; // find out each word in reversed string and then reverse it. string res; while ( sp <= end){ //find the first char that is not space in the remainning of string. if (s[sp] == ' ') { sp++ ; continue;} ep = sp; // do not use ep = sp+1; which will raise the complexity of the contorling. while ( ep <= end ) { if(ep == end ) { //this is the last word. break out all the loop. _reverseWord(s, sp, ep); res += s.substr(sp, ep-sp+1) ; goto RETURN ; } if ( s[ep] != ' ') { ep++; continue;} //now the s[ep] is ' ', and a whole word is marked bu [sp, ep); _reverseWord(s, sp, ep-1); res += s.substr(sp, ep-sp) + " "; sp = ep ; break; } } RETURN: // copy the destination string back to s. s = res.substr(0, res.size()); } };