题目
原文:
Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.
FOLLOW UP
Write the test cases for this method.
译文:
设计算法并写出代码移除字符串中重复的字符,不能使用额外的缓存空间。注意: 可以使用额外的一个或两个变量,但不允许额外再开一个数组拷贝。
进一步地,
为你的程序写测试用例。
解答
这道题目其实是要你就地(in place)将字符串中重复字符移除。你可以向面试官问清楚, 不能使用额外的一份数组拷贝是指根本就不允许开一个数组,还是说可以开一个固定大小, 与问题规模(即字符串长度)无关的数组。
如果根本就不允许你再开一个数组,只能用额外的一到两个变量。那么,你可以依次访问 这个数组的每个元素,每访问一个,就将该元素到字符串结尾的元素中相同的元素去掉( 比如置为' ').时间复杂度为O(n2 ),代码如下:
void removeDuplicate(char s[]) { int len = strlen(s); if(len < 2) return; int p = 0; for(int i=0; i < len; ++i) { if(s[i] != '