刪除字串中的某些字母O(N)時間O(1)空間

來源:互聯網
上載者:User

這個方法是用了hash方法,將要刪除的字母先用數組下表表示,如果要刪除,則標記為1.不需要刪除的標記為0

這個方法在刪除元素的時候比較巧妙,它對要刪除的字元並不主動刪除,而是將空間留在那裡,讓後面不需要被刪除的字元去覆蓋。

具體實現如下:

string& f(string& str,const string& deles){bitset<256> hash;hash.reset();for (int i=0;i<deles.size();i++){hash[deles[i]]=1;}int slow=0,fast=0;while(fast<str.size()){if (hash[str[fast]]==1){fast++;//跳過表示刪除了,準備被後面留下來的字元覆蓋continue;}str[slow++]=str[fast++];}str.resize(slow);return str;}int main( void ) {string s="They are students.";cout<<s<<endl;cout<<f(s,"aeiou")<<endl;return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.