字符串刪除指定字符


一、算法描述

    給定一個字符串和模式字符串,要求將出現在模式字符串的字符在原字符串中刪除。

 

二、算法思路

    從題面理解,常規思路是遍歷原字符串和模式字符串,將原字符串的每個字符和模式串的每個字符比較,如果比較相等,則不輸出,其時間復雜度為O(m*n),m和n各自為字符串和模式字符串的長度;另一種高效的思路是以空間換時間,借助hash數組,標記模式字符串中每個出現的字符,hash數組以字符的ascii碼值為下標,所以其大小一般為256,然后遍歷原字符串,判斷字符是否在hash數組中,不在的話則輸出。

 

三、算法代碼

    下面給出這種方法的代碼

#include <iostream>
#include <cstring>
using namespace std;
//o(m*n),m=>string length, n==>pat length
void del_pat_char(char *s,int n,const char *pat)
{
    int i=0,j=0;
    int lp=strlen(pat);    
    for(i=0;i<n;++i)
    {
        for(j=0;j<lp && pat[j]!=s[i];++j)
            ;
        if(j>=lp)
        {
            cout<<s[i];
        }
    }
    cout<<endl;
    
}
//o(n)
void del_pat_char_2(char *s,int n, const char *pat)
{
    int i=0,j=0;    
    int *pHash=new int[256];
    memset(pHash,0,sizeof(int)*256);
    while(*pat)
    {
        pHash[*pat]=1;
        pat++;
    }
    for(i=0;i<n;++i)
    {
        if(!pHash[s[i]])
            cout<<s[i];
    }
    cout<<endl;
    
}
int main()
{
    char str[256]="You are the best people";const char pat[256]="plbte";
    del_pat_char(str,strlen(str),pat);
    del_pat_char_2(str,strlen(str),pat);
    return 0;
}


免責聲明!

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



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