字符串去重经常会考的笔试题目,这里列出几种常用的方法
更详细的解释(C++版本)请参考http://hawstein.com/posts/1.3.html
解法一:取第一个字符然后遍历后面所有字符,若有重复的则将后面的字符设置为'\0'
//将重复字符设置为'\0'
void RemoveDuplicate(char *str)
{
int i, j, k, len;
len = strlen(str);
for(i = k = 0; i < len; i++)
{
if(str[i])
{
str[k++] = str[i];
for(j = i + 1; j < len; j++)
if(str[j] == str[i])
str[j] = '\0';
}
}
str[k] = '\0';
}
解法二:设置一个标记数组,检查是否有重复字符出现,若没有出现过则插入字符串
void RemoveDuplicate(char *s)
{
char check[256] = { 0 };
int i, j, len;
len = strlen(s);
for(i = j = 0; i < len; i++)
{
if(check[s[i]] == 0)
{
s[j++] = s[i];
check[s[i]] = 1;
}
}
s[j] = '\0';
}
进一步优化,这里标记数组用了256个字节,我们可以用含有8个整型元素的数组来表示
void RemoveDuplicate(char *s)
{
int i, j, len, remainder;
int check[8] = {0};
len = strlen(s);
for(i = j = 0; i < len; i++)
{
remainder = s[i] % 32;
if((check[s[i] >> 5] & (1 << remainder)) == 0)
{
s[j++] = s[i];
check[s[i] >> 5] |= (1 << remainder);
}
}
s[j] = '\0';
}
继续压缩问题,如果字符串中只出现a~z之间的小写字母,可用一个整型变量表示
void RemoveDuplicate(char *s)
{
int i, j, val, check;
j = check = 0;
for(i = 0; s[i]; i++)
{
val = s[i] - 'a';
if((check & (1 << val)) == 0)
{
s[j++] = s[i];
check |= 1 << val;
}
}
s[j] = '\0';
}