(面试题)删除在另一个字符串中出现的字符
生活随笔
收集整理的這篇文章主要介紹了
(面试题)删除在另一个字符串中出现的字符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符。例如,輸入”They are students.”和”aeiou”,則刪除之后的第一個字符串變成”Thy r stdnts.”。
思路:
通過hash表記錄第二個字符串中出現的字符,hash表可以由長度為256的bool數組表示。
然后遍歷第一個字符串,每掃描一個字符,通過檢查hash表判斷該字符是否在第二個字符串出現過,如果是,則刪除,否則繼續。
那么如果在字符串中刪除字符呢?一般而言,每刪除一個字符,后面的字符必須往前移,如果每個字符都需要這么操作的話,復雜度就很高了。
解決辦法:通過兩個指針,一個用于遍歷字符串pFast,一個用于刪除字符pSlow,當pFast指針所指字符沒有在第二個字符串出現過,則*pSlow=*pFast,pSlow++,即保留該位置的字符,否則,pSlow不變,當遍歷完字符串之后,*pSlow='\0',以表示刪除字符后的新字符串。
代碼:
#include <iostream>using namespace std;void deleteChars(char* str1,char* str2){if(str1==NULL || str2==NULL)return;const int tableSize=256;bool hashTable[tableSize];for(int i=0;i<tableSize;i++)hashTable[i]=false;//memset(hashTable,0,sizeof(tableSize));int index;while(*str2!='\0'){if(*str2>=0)index=*str2;elseindex=*str2+256;hashTable[index]=true;str2++;}char* pSlow=str1;char* pFast=str1;while(*pFast!='\0'){if(*pFast>=0)index=*pFast;elseindex=*pFast+256;if(!hashTable[index]){*pSlow=*pFast;pSlow++;}pFast++;}*pSlow='\0'; }int main() {char str1[] = "They are students";char str2[] = "Tt";deleteChars(str1,str2);cout<<str1<<endl;return 0; }轉載于:https://www.cnblogs.com/AndyJee/p/4676608.html
總結
以上是生活随笔為你收集整理的(面试题)删除在另一个字符串中出现的字符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: location.pathname;ou
- 下一篇: 转:“401 - 未授权:由于凭据无效,