翻轉字串——不用額外的記憶體空間
阿新 • • 發佈:2018-11-21
描述
給定一個字串,逐個翻轉字串中的每個單詞。
說明
單詞的構成:無空格字母構成一個單詞
樣例
給出s = “the sky is blue”,返回"blue is sky the"
使用額外空間的思路
使用std::string的find_first_of,以’ '為引數,將s分割成多個單詞並推進堆疊中,然後利用堆疊的先進後出的特點,以彈出的順序去得到逆序的字串。這樣會使用額外的空間來暫存堆疊的資料。
挑戰:不使用額外空間
在原先的s的基礎上,利用兩個索引:tail , head將s整個翻轉,得到eulb si yks eht
可以觀察的到,eulb si yks eht與目標結果:blue is sky the的差別在於,前者每個單詞都是反的。
故可以使用std::string的find_first_of,以’ '為引數,將s分割成多個單詞,每個單詞再次使用上述方式:使用tail,head整體翻轉,即可得到目標結果。
string reverseWords(string &s) { // write your code here int tail = s.size() - 1; int head = 0; //先全部翻轉 while (head < tail) { char temp = s[head]; s[head] = s[tail]; s[tail] = temp; head++; tail--; } //再逐單詞逐單詞翻轉,這樣可以達到無需任何額外的空間即可翻轉成功 found = s.find_first_of(' '); int curr = 0; bool flag = true; while (flag) { if (found == std::string::npos) {//最後一串 found = s.size(); flag = false;//break the while } // temp_str = s.substr(curr, found - curr); //翻轉temp tail = found-1;//-1為去除空格 head = curr; while (head < tail) { char temp = s[head]; s[head] = s[tail]; s[tail] = temp; head++; tail--; } curr = found+1; found = s.find_first_of(" ", found + 1); } return s; }