您的位置:首页 > 其它

从字符串中删除重复的字符

2013-02-15 02:01 435 查看
设计一个算法去移除字符串中重复的字符,但是只可以使用一个或两个变量的额外空间。

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

is fine. An extra copy of the array is not. pg 22

为算法写出测试用例。

FOLLOW UP

Write the test cases for this method.

解:

SOLUTION

First, ask yourself, what does the interviewer mean by an additional buffer? Can we use an

additional array of constant size?

不用额外空间的解法:

将原数组分为两边,一边为不重复的字符串a,另一边为要处理的字符串b。

对于b中的字符,检查他是否在a中出现,如果出现了,处理b中的下一个字符,如果没有出现,将其添加到a中。

时间复杂度为O(N2).

初始时a中有一个字符。

Algorithm—No (Large) Additional Memory:

1. For each character, check if it is duplicate of already found characters.

2. Skip duplicate characters and update the non duplicate characters.

Time complexity is O(N2).

void removeDuplicates(char *str) {
if (!str)
return;
int len = strlen(str);
if (len < 2)
return;
int tail = 1;
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j)
if (str[i] == str[j])
break;
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
str[tail] = 0;
}


Test Cases:

1. String does not contain any duplicates, e.g.: abcd

2. String contains all duplicates, e.g.: aaaa

3. Null string

4. String with all continuous duplicates, e.g.: aaabbb

5. String with non-contiguous duplicate, e.g.: abababa

使用额外空间的算法:

使用hit数组记录字符是否重复,如果为true表示在未重复的字符串中。

Algorithm—With Additional Memory of Constant Size

void removeDuplicatesEff(char *str) {
if (!str)
return;
int len = strlen(str);
if (len < 2)
return;
bool hit[256];
for(int i = 0; i < 256; ++i)
hit[i] = false;
hit[str[0]] = true;
int tail = 1;
for (int i = 1; i < len; ++i) {
if (!hit[str[i]]) {
str[tail] = str[i];
++tail;
hit[str[i]] = true;
}
}
str[tail] = 0;
}
Test Cases:

1. String does not contain any duplicates, e.g.: abcd

2. String contains all duplicates, e.g.: aaaa

3. Null string

4. Empty string

5. String with all continuous duplicates, e.g.: aaabbb

6. String with non-contiguous duplicate, e.g.: abababa











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