How to check if a string has all unique characters

GitHub:  solution 1.1

  • Check if the string is an ASCII string.

There are many different solutions, I practiced with a HashSet. Time complexity: O (n).

	public static boolean isUniqueChars3(String str){
		if (str.length() > 256){
			return false;
		}
		HashSet  uniCharSet = new HashSet();
		boolean result = false;

		for(int i = 0; i < str.length(); i++){
			result = uniCharSet.add(str.charAt(i));
			if (result == false)
				break;
			result = true;
		}
		return result;
	}

from Cracking the Code Interview , isUniqueChars2 is an insteresting solution. A good source to explain the solution: trying to understand: checker |= (1 << val)

	public static boolean isUniqueChars(String str) {
		if (str.length() > 128) {
			return false;
		}
		int checker = 0;
		for (int i = 0; i < str.length(); i++) {
			int val = str.charAt(i) - 'a';
			if ((checker & (1 < 0) return false;
			checker |= (1 << val);
		}
		return true;
	}

Reference:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s