Cracking the coding interview--Q1.3

题目:

原文:

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.

译文:

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

更进一步,为你的方法写出测试用例。

解答:

这道题刚看的时候发现并不难的,但一些细节bug却花了我很多时间都没弄明白,首先困扰我的是题目说的是字符串string,但网上很多解答都是当做字符数组char[],还有网上的基本都是C++解答的,而我用java参考那些方法,发现不行。发现一个低级的错误,就是java的String是没有结束符'\0',这是和C,C++不同之处(太不一样了);还有书上提供的解答是不对的,一直出现ArrayIndexOutOfBoundsException; 还有'\0'在java的char[]中会被打印为空格……

最后只弄了一个比较挫的方法,就是用循环遍历一遍数组,找出相同的字符,标记为特定字符(此处有缺陷,不能标记为'\0',因此字符集的有局限性),然后再用一个循环将后面字符覆盖之前的标记的特定字符,……看代码如下:

class Q1_3{
	public static String remove(char[] str){
		int len=str.length;
		if(len<2) return new String(str);
		int k=0;
		for(int i=0;i<len-1;i++){
			for(int j=i+1;j<len;j++){
				if(str[i]==str[j]){
					str[j]='-';
				}
			}
		}
		for(int i=0;i<len;i++){
			if(str[i]!='-'){
				str[k]=str[i];
				++k;
			}
		}
		return (new String(str)).substring(0,k);
	}
	

	public static void main(String[] args){
		//测试用例:
		//不含重复字符的,如abcd
		//全部都是重复字符的,如aaaa
		//空字符串
		//包含重复字符,如aabb
		String str="abcd";
		String str1="aaaa";
		String str2="";
		String str3="aabb";
		
		char ss1[] = {'a','b','c','d'};
		char ss2[] = {'a','a','a','a'};
		char ss3[] = {};
		char ss4[] = {'a','a','b','b'};

		System.out.println(remove(ss1));
		System.out.println(remove(ss2));
		System.out.println(remove(ss3));
		System.out.println(remove(ss4));
	}
}

头脑短路了,此方法太挫了,求更好的解法!

---EOF---


你可能感兴趣的:(Cracking the coding interview--Q1.3)