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.
这道题做的时候思维上有问题。每次发现有重复的就将其后的向前移位。看了答案才明白不需要移位,中间留一段无效的地带就可以。
#include <iostream>
using namespace std;
void removeDuplicates(char* str) {
if (str == NULL) return;
char *p, *q, *tail;
tail = str + 1;
for(p=str; *p!='\0'; p++)
{
for(q=str; q<tail; q++)
{
if(*q == *p) break;
}
if(q==tail)
{
*tail++ = *p;
}
}
*tail = '\0';
};
int main()
{
char str[] = "aabcdefgeeadaa";
removeDuplicates(str);
cout<<str;
system("pause");
};
本文介绍了一种使用C++实现的高效算法,用于去除字符串中的重复字符,仅使用一到两个额外变量,不借助额外缓冲区。通过实例代码演示,对比常规方法在处理大量数据时的效率提升。

571

被折叠的 条评论
为什么被折叠?



