数据结构练习(26)在字符串中删除特定的字符
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; }
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------