CH1-3: remove duplicate char in a string, with/without additional buffer
来源:互联网 发布:淘宝网大童长款皮衣 编辑:程序博客网 时间:2024/05/16 14:25
感谢Hawstein的答案,然后再整理一边,make sure自己完全理解了。
所有代码在http://www.compileonline.com/compile_cpp11_online.php 上面测试,方便快捷,同时在本地和csdn git上面备份。
1. 记录各个字符出现情况的bool型scoreboard可以保存下标大于size的吗?
其实没关系,因为ASCII的decimal范围是0~127(其实还有128个,那些是extended ASCII,所以需要8位来保存全部的ascii码)。所以所有值都在0~255;
eg:
bool a[256]; //cuz it stored the ASCII memset(a,0,sizeof(a));void block(char* s){ const int* curptr = s; for (int i = 0; i<len; ++i){ int v = *curptr; curptr++; a[v] = true; // eg: A的ASCII值是65,a的是97 }}
但是就算是定义了一个size为1的array:a[1],也可以定义a[300],a[301],a[302]...不知道为什么。。。
2种情况的T(n)会不一样:
1. 如果不可以用另外的array的话,就要In place 的修改,也就是见到一个char就和他后面的所有字符比较一遍,当发现duplicate的情况,把那个字符置为一个flag的值,好让后面s[p++]=s[i]的时候的判定是根据(s[i]!=flag). Hawstein的flag是‘\0’,这样就不用想一个不是ASCII的字符了。不过这样就不会复制最后一个真正的结束符号,所以在循环完之后要s[p] = '\0'. 记得K&R的解答也用了这个方法。
当然,用这个方法的话,T(n)=n+(n-1)+(n-2)+...+1 = O(n^2);
2. 如果可以用additional buffer,则只需要1次循环,而modify一遍scoreboard需要O(n)的时间复杂度。
在这里的2个method都是针对输入是char型字符串:char ss1[] = "abcde";
而如果是string的话,就要用string的method,修改的话 需要用str+=,而不能s[p++].
- CH1-3: remove duplicate char in a string, with/without additional buffer
- How do you remove the duplicate characters in a given string without using any additional buffer.
- Ch2-1: de-duplicate a linked-list with/without additional buffer
- 【3】Remove the duplicate characters in a string
- Ch1-5: Write a method to replace all spaces in a string with ‘%20’.
- [CrackCode] 1.3 Remove the duplicate characters in a string
- careercup1.3: remove duplicate without extra space.
- char * strtrim(char* s ) to remove any space character(such as '\t' , ' ' ...) in a string
- remove the duplicate(重复) characters from a string
- remove duplicated chars in a string
- Remove Duplicate Numbers in Array
- 深入char buffer[]与string
- How to encrypt a string/stream with bouncycastle pgp without starting with a file
- 按单词(word)反转字符串(string)输出(output)——不用额外缓存(without a buffer)
- Search String in a String array with empty string
- How to remove the duplicated value in a String array
- A First Course in Database Systems - notes ch1
- Remove duplicate in sorted linked list 1
- hbase 集群管理脚本
- HBase集群部署脚本
- HBase表重命名
- HBase 快照操作
- 三星Galaxy Note II LTE/T889刷机教程/破解教程/ROM/刷机包下载索引
- CH1-3: remove duplicate char in a string, with/without additional buffer
- 图像处理的简单优化-03:优化-消除临时变量
- LeetCode: Linked List Cycle
- 图像处理的简单优化-04:循环消弱
- C++常用字符串长度计算函数
- linux下的c++(base 1)
- 图像处理的简单优化-05:评估
- Android手机访问Django测试服务器方法
- 硬件工程师的系统开发之路