您的位置:首页 > 理论基础 > 数据结构算法

数据结构练习(26)在字符串中删除特定的字符

2012-12-17 15:03 225 查看
http://zhedahht.blog.163.com/blog/static/25411174200801931426484/

思路:

关于删除字符处理的特别巧妙,双指针移动的方法,最终时间复杂度为O(n).

需要注意的一点是:最后不能忘记给src字符串加上'\0'

#include <iostream>
#include <cstring>
using namespace std;

void DeleteChars(char *src, const char *dst)
{
if (!src || !dst)
return;

const int hashsize = 256;
int hash[hashsize];
memset(hash, 0, sizeof(hash));

const char *p = dst;
while (*p != '\0')
{
hash[*p] = 1;
++p;
}

char *pfast = src;
char *pslow = src;

while (*pfast != '\0')
{
if (hash[*pfast] != 1)
{
*pslow = *pfast;
++pslow;
}
++pfast;
}
*pslow = '\0';
}

int main()
{
char s1[100] = "They are students.";
char s2[100] = "aeiou";
DeleteChars(s1, s2);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: