牛客最近來了一個新員工Fish,每天早晨總是會拿著一本英文雜誌,寫些句子在本子上。同事Cat對Fish寫的內容頗感興趣,有一天他向Fish借來翻看,但卻讀不懂它的意思。
阿新 • • 發佈:2018-11-22
題目描述
牛客最近來了一個新員工Fish,每天早晨總是會拿著一本英文雜誌,寫些句子在本子上。同事Cat對Fish寫的內容頗感興趣,有一天他向Fish借來翻看,但卻讀不懂它的意思。例如,“student. a am I”。後來才意識到,這傢伙原來把句子單詞的順序翻轉了,正確的句子應該是“I am a student.”。Cat對一一的翻轉這些單詞順序可不在行,你能幫助他麼?
/*
思路1:兩次翻轉
先將字串整體翻轉
再一次翻轉每個單詞
*/
class Solution { public: string ReverseSentence(string str) { int len = str.length(); string &temp = str; reserve(temp,0,len-1); int s = -1; for(int i=0;i<len;i++){ if(str[i] == ' '){ reserve(temp,s+1,i-1); s = i; } } reserve(temp,s+1,len-1); return str; } void reserve(string &s,int start,int end){ char temp; while(start < end){ temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } } };
/*
思路2:
利用分割函式將單詞切割,並儲存在數組裡;
然後按照從後往前的陣列順序,依次拼接字串。
*/
class Solution { public: string ReverseSentence(string str) { vector<string> tempv = split(str," "); string res; for(int i=tempv.size()-1;i>=1;i++){ res = res + tempv[i] + ' '; } res = res + tempv[0]; return res; } vector<string> split(const string& str, const string& delim) { vector<string> res; if("" == str) return res; //先將要切割的字串從string型別轉換為char*型別 char * strs = new char[str.length() + 1] ; //不要忘了 strcpy(strs, str.c_str()); char * d = new char[delim.length() + 1]; strcpy(d, delim.c_str()); char *p = strtok(strs, d); while(p) { string s = p; //分割得到的字串轉換為string型別 res.push_back(s); //存入結果陣列 p = strtok(NULL, d); } return res; } };