careercup 1.1: unique characters

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

 

package careercup;

public class test1 {
	/*Implement an algorithm to determine if a string has all unique characters. What if you 
	can not use additional data structures?*/
	public static boolean checkUnique(String s) {
		if(s.length()<1) return true;
		
		final int ASC_MAX = 256;
		boolean[] flags = new boolean[ASC_MAX];
		
		for(int i=0; i<s.length(); i++) {
			if(flags[ s.charAt(i) ]){
				return false;
			} else {
				flags[s.charAt(i)] = true;
			}
		}
		return true;
	}
	
	public static boolean checkUniqueInt(String s){
		if(s.length()<1) return true;
		
		int checker=0;
		for(int i=0; i<s.length();i++) {
			if( (checker & (1<< (s.charAt(i)-'a'))) ==1 ) {
				return false;
			} else{
				checker |= 1<<(s.charAt(i)-'a');
			}
		}
		return true;
	}
	
	public static void main(String[] args){
		String s = "asdfghjkl";
		System.out.println( checkUnique(s) );
	}
	
}


 

posted @ 2013-01-31 08:26  西施豆腐渣  阅读(181)  评论(0编辑  收藏  举报