Arrays_Strings 判断字符串中的字符是否唯一@CareerCup

原文:

Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

译文:

实现一个算法来判断一个字符串中的字符是否唯一(即没有重复).不能使用额外的数据结构。 (即只使用基本的数据结构)


思路:

1 暴力比较,两个for循环,O(n^2)

2 如果可以改变原字符串的字符,则可以用O(nlogn)排序,然后比较邻居字符是否一样


3 虽然不能用其他数据结构(Hashtable),但可以用array来模拟哈希表。Time: O(n), Space: O(1)

4 如果字符串只包含小写字符或者只包含大写字符,则可以用一个32位的integer代替array。


package Arrays_Strings;

public class S1_1 {

	
	// 第一种方法,开一个辅助数组存放
	// Time O(n), Space O(1)
	public static boolean isUniqueChars(String s) {
		if(s.length() > 256) {		// 预先判断字符串个数,如果超过256,根据抽屉原理,必有重复
			return false;
		}
		
		boolean[] used = new boolean[256];
		for (int i=0; i<s.length(); i++) {
			if(used[s.charAt(i)]) {
				return false;
			}
			used[s.charAt(i)] = true;
		}
		return true;
	}
	
	// 第二种方法,通过bit vector来减少空间
	// 如果字符串只包含小写字符或大写字符,则可以使用,因为26<32
	public static boolean isUniqueChars2(String str) {
		if (str.length() > 256) {
			return false;
		}
		
		int checker = 0;
		for(int i=0; i<str.length(); i++) {
			int val = str.charAt(i) - 'a';
			if((checker & (1<<val)) > 0) {		// 检查checker的左起第i位
				return false;
			}
			checker |= (1<<val);	// 把checker的左起第i位置1
		}
		
		return true;
	}
	
	public static void main(String[] args) {
		String[] words = {"abcde", "hello", "apple", "kite", "padle"};
		for (String word : words) {
			System.out.println(word + ": " + isUniqueChars(word) + " " + isUniqueChars2(word));
		}
	}
}


重新捡起cc150。。。


你可能感兴趣的:(Arrays_Strings 判断字符串中的字符是否唯一@CareerCup)