String of all unique characters?

function isUnique(str){

	//more than 256 chars means at least one is not unique assuming ASCII
	if( str.length>256 ) { return false; } 

	    //array for which chars have been used
	    var char_set = [];
	    var i;

	    //iterate over the string
	    for( i = 0; i < str.length; i++ ) {

	        val = str[i];

	        //if this has been set to true this char is not unique
	        if( char_set[val] ) {
	            return false;
	        }

	        //record this char
	        char_set[val] = true;
	    } 

	//string is unique
	return true;
}
document.writeln(isUnique('abcd'));
document.writeln(isUnique('abcdd'));

Leave a Reply

You must be logged in to post a comment.