算法题:剔除字符串(非常有意思)

/*
两个字符串A、B。从A中剔除存在于B中的字符。
比方A = “hello world”, B = "er",那么剔
除之后A变为"hllo wold"。空间复杂度要求是O(1)
。时间复杂度越优越好。
*/
#include <iostream>
#include <string.h>
using namespace std;
void Grial(char *str,char *ptr)
{
    char sP[32];//用32个char表示字符表。
    memset(sP,'',sizeof(sP));//这里必须清零。

char *p = ptr; while (*p != '') { sP[*p >> 3] |= (0x1 << (*p & 0x7)); p++; //将ptr映射到32个char型的数组里面,假设存在就将 //其位置1。 } p = str; char *q = p; while (*p != '')//開始剔除。

{ if (sP[*p >> 3] & (0x1 << (*p & 0x7))) { p++; } else { if (q!=p) *q = *p; q++; p++; } } *q = ''; } int main() { char A[] = "hello word"; char B[] = "er"; Grial(A, B); cout << A << endl; return 0; }

原文地址:https://www.cnblogs.com/yutingliuyl/p/7150530.html