您的位置:首页 > 其它

【Cracking the coding interview】Q1.3(移除重复字符)

2013-12-23 19:18 423 查看
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.

设计算法并写出代码移除字符串中重复的字符,不能使用额外的缓存空间。注意: 可以使用额外的一个或两个变量,但不允许额外再开一个数组拷贝。

进一步地,为你的程序写测试用例。

思路,类似Q1.1 用一个bool辅助数组来做

#include<iostream>
#include<cstring>
#include<stdlib.h>

using namespace std;

//char s[]数组
void removeduplicate(char s[]){
bool check[256];
memset(check, false, sizeof(check));//这句很重要
int p=0,i=0;
int len=strlen(s);
while(i<len){
if(!check[s[i]]){
s[p++]=s[i];
check[s[i]]=true;
}
i++;
}
s[p]='\0';
}
//string

string removeduplicatestring(string s){

int len=s.length();
if(len<2)
return s;
int check=0,i=0;
string str="";

while(i<len){
if(!(check&(1<<(s[i]-'a')))){
str +=s[i];
check |=1<<(s[i]-'a');
}

i++;
}
return str;

}

int main(){
char s[]="1dadf";
removeduplicate(s);
cout<<s<<endl;
string s2="abcdeaf";

cout<<removeduplicatestring(s2);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: