劍指offer(C++)——替換空格__C++

來源:互聯網
上載者:User
題目描述

請實現一個函數,將一個字串中的空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

思路:簡單暴力解法,從頭到尾遍曆字串,碰到空格,首先將後面的所有字串往後移動2個字元,才能空出3個字元位子插入字元“%20”,對於一個長度為n的字串,對每個空格,需要移動後面O(n)個字元,因此包含n個空格的字串,總的時間複雜度為O(n*n)。

換個角度,我們從後往前開始替換,首先遍曆一遍字串,統計出空格的個數,並由此能夠計算出替換之後的字串的長度。接著再次從後往前遍曆字串,同時設定兩個指標P1和P2,P1指向原始字串末尾,P2指向替換之後的字串末尾。我們向前移動P1,逐個把它指向的字元複製到P2指向的位置,直到碰到第一個空格為止。然後把P1向前移動一格,在P2之前插入字串“%20”,同時P2向前移動3格。重複此過程,直到所有的空格都已替換完。這種做法的時間複雜度為O(n)。

代碼實現:

class Solution {public:void replaceSpace(char *str, int length) {if (str == NULL || length < 0)return;else{int numoforiginal = 0;            //用來統計字串長度int numofspace = 0;                //用來統計空格數int i = 0;while (str[i] != '\0'){numoforiginal++;               //統計字串長度if (str[i++] == ' ')numofspace++;              //空格數}int newoflength = numoforiginal + numofspace * 2;if (newoflength > length)return;//從後往前替換空格int indexoforiginal =numoforiginal;                          int indexofnew = newoflength;while (indexoforiginal >= 0 && indexofnew > indexoforiginal){if (str[indexoforiginal] == ' '){str[indexofnew--] = '0';str[indexofnew--] = '2';str[indexofnew--] = '%';}elsestr[indexofnew--] = str[indexoforiginal];indexoforiginal--;}}}};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.