/*
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>
#include <string>
using namespace std;
void removeDuplicates(string &str)
{
int len = str.length();
if(len < 2)
return;
//new_end为无重复元素数组末元素下一位置的下标
int new_end = 1;
for (int i = 1;i < len;++i)
{
int j;
//判断str[0...new_end-1]和str[i...len-1]是否有相等元素
for (j = 0;j < new_end;++j)
{
//str[i]与str[0...new_end-1]中元素相等,则跳出for循环,接着判断str[i+1]
if (str[j] == str[i])break;
//str[i]不与str[0...new_end-1]中元素相等,则令str[new_end]等于str[i]
}
if(j == new_end)
{
str[new_end] = str[i];
++new_end;
}
}
str[new_end] = '\0';
}
void print_c_str(string str)
{
for (int i = 0;i < str.length();++i)
{
if(str.at(i) == '\0')
break;
cout << str[i];
}
cout << endl;
}
int main()
{
string s1 = "";
string s2 = "aaaa";
string s3 = "aaaabbbb";
string s4 = "abababab";
removeDuplicates(s1);
removeDuplicates(s2);
removeDuplicates(s3);
removeDuplicates(s4);
print_c_str(s1);
print_c_str(s2);
print_c_str(s3);
print_c_str(s4);
return 0;
}
remove the duplicate(重复) characters from a string
最新推荐文章于 2019-03-04 13:04:30 发布