(面試題)刪除在另一個字符串中出現的字符


題目:

輸入兩個字符串,從第一字符串中刪除第二個字符串中所有的字符。例如,輸入”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;
        else
            index=*str2+256;
        hashTable[index]=true;
        str2++;
    }

    char* pSlow=str1;
    char* pFast=str1;
    while(*pFast!='\0'){
        if(*pFast>=0)
            index=*pFast;
        else
            index=*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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM