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

23 篇文章 0 订阅
7 篇文章 0 订阅

设计一个算法去移除字符串中重复的字符,但是只可以使用一个或两个变量的额外空间。

 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











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值